How to generate the first n terms in the series:
Here is slightly different option
f <- function(a1 = 1, n = 10) {
ret <- numeric(n) # Pre-allocation
ret[1] <- a1
for (i in 2:length(ret)) ret[i] <- 5 * ret[i - 1] + 3 ^ (i - 1)
ret
}
f(n = 10)
#[1] 1 8 49 272 1441 7448 37969 192032 966721
#[10] 4853288
Two small comments:
- We initialise the vector with
numeric(n)
which is faster than doing e.g.rep(0, 10)
. - The rest is just a classic
for
loop that starts at the second index of the return vector.
Or a C++ solution using Rcpp
library(Rcpp)
cppFunction("
IntegerVector f2(int n = 10, int a1 = 1) {
IntegerVector ret(n, a1);
for (int i = 1; i < n; i++) {
ret[i] = 5 * ret[i - 1] + pow(3, i);
}
return ret;
}")
f2(10)
# [1] 1 8 49 272 1441 7448 37969 192032 966721
#[10] 4853288
And a microbenchmark
comparison
library(microbenchmark)
res <- microbenchmark(
R_for_loop = f(n = 10),
Rcpp_for_loop = f2(n = 10)
)
#Unit: microseconds
# expr min lq mean median uq max neval cld
# R_for_loop 3.226 3.4195 3.78043 3.4945 3.5625 29.365 100 b
# Rcpp_for_loop 1.913 2.0980 2.36980 2.2560 2.3495 12.582 100 a
library(ggplot2)
autoplot(res)
Sum of the first nth term of Series
I took a look at the link you sent, and I suggest that you generate the list depending on the value of n
so that you don't get an IndexError
:
def series_sum(n):
fractions = []
for n in range(1, 3*n - 1, 3):
fractions.append(1/n)
return "{:.2f}".format(sum(fractions))
I tested the code on the website, and it worked for all the solutions.
What is the formula to calculate this sequence?
It looks like the (i+1)-st element is created from the i-th by adding an increasing number:
- a0 = 2, d0 = 3
- a1 = 2+3 = 5, d0 = 4
- a2 = 5+4 = 9, d0 = 5
- a3 = 9+5 = 14, d0 = 6
- a4 = 14+6= 20, d0 = 7
- a5 = 20+7= 27, d0 = 8
- ...and so on
You can compute this result by incrementing d
as you walk through the loop, and adding it to the previous value of a
.
According to the Online Encyclopedia of Integer Sequences, elements of this sequence could be computed using this closed-form expression:
n*(n+3)/2
Note: The above division always produces an integer value because one of n
or n+3
will be even.
How to take the first N items from a generator or list?
Slicing a list
top5 = array[:5]
- To slice a list, there's a simple syntax:
array[start:stop:step]
- You can omit any parameter. These are all valid:
array[start:]
,array[:stop]
,array[::step]
Slicing a generator
import itertools
top5 = itertools.islice(my_list, 5) # grab the first five elements
You can't slice a generator directly in Python.
itertools.islice()
will wrap an object in a new slicing generator using the syntaxitertools.islice(generator, start, stop, step)
Remember, slicing a generator will exhaust it partially. If you want to keep the entire generator intact, perhaps turn it into a tuple or list first, like:
result = tuple(generator)
Generate an array of the first M N-Bonacci Numbers
We know that:
BN(i) = BN(i-1) + BN(i-2) + ... + BN(i-N)
That means that
BN(i-1) = BN(i-2) + BN(i-3) + ... + BN(i-N) + BN(i-N-1)
All I did there was substitute i-i
for i
in the definition.
In other words (subtracting the last term from both sides of the equality):
BN(i-1) - BN(i-N-1) = BN(i-2) + BN(i-3) + ... + BN(i-N)
Now, I substitute this equation back into the first one. (You can see that the right-hand side of this equality is precisely the trailing part of the first equation, so I can substitute the left-hand side of this equality.)
BN(i) = BN(i-1) + BN(i-1) - BN(i-N-1)
That gives you the simplified formula, which can be evaluated without a loop.
Python: Creating a List of the First n Fibonacci Numbers
Try this, a recursive implementation that returns a list of numbers by first calculating the list of previous values:
def fib(n):
if n == 0:
return [0]
elif n == 1:
return [0, 1]
else:
lst = fib(n-1)
lst.append(lst[-1] + lst[-2])
return lst
It works as expected:
fib(8)
=> [0, 1, 1, 2, 3, 5, 8, 13, 21]
I'm not able to step up terms in fibonacci sequence python
The problem is that you use print
at the lowest level, so it is not possible to filter anything from a higher level. If you want to be able to filter, the low fibo_sequence(n)
function should not print anything but should return a sequence. A simple way would be to use a list:
# Program to display the Fibonacci sequence up to n-th term
def fibo_sequence(n):
seq = []
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if n <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif n == 1:
print("Fibonacci sequence upto",n,":")
seq.append(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < n:
seq.append(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
return seq
But it would still not follow good encapsulation pratices, because the same function shows messages and build the sequence. You should only build the sequence (optionaly an empty list) and let the caller decide what to display if the length of the returned list is 0 or 1.
If you want to go further, you should considere to build a generator that would yield
the values one at a time, and because of that would avoid to store them.
Write a program to compute the sum of the terms of the series
How about an explicit formula?
def sumSeries(n):
if n / 4 % 2 == 0:
return - n / 2
else:
return (n + 4) / 2
The series doesn't do anything too interesting, it just keeps adding +4
every two steps, and flips the sign in even steps:
4 = 4
4 - 8 = -4
4 - 8 + 12 = 8
4 - 8 + 12 - 16 = -8
...
Some examples:
for n in range(4, 100, 4):
print("%d -> %d" % (n, sumSeries(n)))
Output:
4 -> 4
8 -> -4
12 -> 8
16 -> -8
20 -> 12
24 -> -12
28 -> 16
32 -> -16
36 -> 20
40 -> -20
44 -> 24
48 -> -24
52 -> 28
56 -> -28
60 -> 32
64 -> -32
Related Topics
Rstudio Suddenly Stopped Showing Plots in the Plot Pane
Removing All Empty Columns and Rows in Data.Frame When Rows Don't Go Away
Add Legend to Geom_Line() Graph in R
Removing Columns That Are All 0
How to Import Multiple .Csv Files At Once
Is R'S Apply Family More Than Syntactic Sugar
How to Get Summary Statistics by Group
Convert Date-Time String to Class Date
Axis Labels on Two Lines With Nested X Variables (Year Below Months)
Adding Value from One Data.Frame to Another Data.Frame by Matching a Variable
Selecting Only Duplicates Based on Multiple Columns in R
How to Add a Row to Data Frame Based on a Condition
Coerce Multiple Columns to Factors At Once
Select the Row With the Maximum Value in Each Group
How to Remove All Duplicates So That None Are Left in a Data Frame
Apply a Function to Every Specified Column in a Data.Table and Update by Reference