get RecursionError when running Fibonacci function - python

def fib(n):
if n == 1 or n == 2:
return 1
return fib(n-1) + fib(n-2)
for i in range(5):
print(fib(i))
I want to print first 5 result of Fibonacci sequence only to get
RecursionError: maximum recursion depth exceeded in comparison
I think there is an exit of every positive n and print(fib(4)), print(fib(20)) and print(fib(100)) works perfectly.
What's wrong with my code?

range(5) starts at 0 and since you are not checking for 0 in your function, the recursion never ends.
As a sidenote, you are not calculating the fibonacci sequence correctly, you should add up
fib(n-1) + fib(n-2)
Try this:
def fib(n):
if n <= 2:
return n
return fib(n-1) + fib(n-2)
A generally better approach at calculating the n-th fibonacci number is to use a loop, since you end up calculating the same values over and over again if you use recursion. Using a loop you can do it like this:
def fibonacci(n):
if n < 2:
return 1
a = 1
fib = 1
for i in range(n-2):
a, fib = fib, a + fib
return fib

there is an exit of every positive n.
Yes, there is. But how about fib(0)?
Try print(list(range(5)))

Related

Python program, no output displayed when i run

python newbie here. I have a code below, but when i run the code nothing displays.
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci (n-1) + fibonacci (n-2)
what am I missing ? is it a print statement ? when i add print (), I get 327 as the result, but i don't think that is Fibonacci series.
This will print out the first 10 fibonacci numbers according to your code. Without a print statement, you will see no output.
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci (n-1) + fibonacci (n-2)
for i in range(10):
print(fibonacci(i))
Your current fibonacci() function just returns the value, you can either take that return value and print it, as I did above, or not return anything and just print the value directly in the function (see below)
def fibonacci(n):
if n <= 1:
print(n)
else:
print(fibonacci (n-1) + fibonacci (n-2))
for i in range(10):
fibonacci(i)

a (recursive) function that will calculate sum for a given n

How to write a recursive function that will calculate this sum for a given n?
n
∑ 1/k
k=1
My code:
def sum(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return sum(1/n) + sum(1/n+1)
print(sum(3))
For n = 3 the output should be: 1.8333333333333333
You should avoid declaring a new function with the name sum as there already exists a built-in function with this name.
You can recursively calculate
n n-1
∑ 1/k == 1/n + ∑ 1/k
k=1 for n > 0 k=1
with
def my_recursive_sum(n):
if n <= 0:
return 0
if n == 1:
return 1
return 1/n + my_recursive_sum(n-1)
print(my_recursive_sum(3))
Your solution would easily reach the maximum recursion limit.
when you call again the function using 1/n and 1/n+1 you would use the same n and increase it, so you would never reach the end condition.
the next couple of sum would never have an n value equal to 0 or 1.
Also you should not call again the function with 1/n otherwise you would endup looping forever in the function recall
you should use something like:
>>> def my_sum(n):
... if n < 1:
... return 0
... return 1/n + my_sum(n-1)
...
>>> print(my_sum(3))
1.8333333333333333
>>> 11/6
1.8333333333333333
>>>
edit:
Like mentioned in another answer you should avoid using sum as a name of a function because it's a name already use by python

Iterating through the Fibonacci sequence

so i'd like to iterate through the Fibonacci sequence (but this could apply to any non-arithmetic sequence). i've written a function fibonacci:
from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
which returns the fibonacci number for any given input. this bit seems to work OK. However, I'd like to include a couple of conditions, like even numbers and F(n) below a certain limit. I tried using an if loop like this:
def ser():
count = 0
for i in F(n):
if F(n) <= 4000000 and F(n) % 2 == 0:
count = count + F(n)
But it seems like you can't use F(n) in the iteration for loop like I did. I'm a complete novice at python, so how would be best to use the F(n) function I created to iterate over the sequence? Thanks
What is the range of n that you are looking to run the fibonacci number on?
Your definition of fibonacci is in a closed form, so you need to give each number you want to calculate:
import itertools
count = 0
for n in itertools.count(1):
if F(n) > 4000000:
break
if F(n) % 2 == 0:
count += F(n)
You can use a generator form of fibonacci and use itertools.takewhile() to limit the output:
def F():
a,b = 0,1
yield b
while True:
a, b = b, a + b
yield b
count = sum(f for f in it.takewhile(lambda x: x <= 4000000, F()) if f % 2 == 0)

a recursive function to calculate sum of a number digits

i have to write a recursive function which calculates sum of a number digits,here's the code i tried :
def sum_digit(n):
sum=0
a = n % 10
n //= 10
sum += a
while n > 0 :
sum = sum + sum_digit(n)
return sum
print(sum_digit(67154))
i don't know why i don't get the 23 as answer...my program doesn't come to an end
for example 23 number(please correct me if I'm wrong,I'm a newbie in python),the 3 goes to sum, and n become2,since its > 0 then it should go to while,so now it should calculate sum digit(2),the a become 2 and 2 goes to sum and n become 0 and sum digit(2) returns 2,then it sum with the 3 and i must get 5.
i appreciate your help.
You have an infinite loop because n never changes within the loop. Note that assigning a new value to n in the scope of the called function will not change n in the outer scope.
Also, it seems you are mixing an iterative solution with a recursive one. If you do the recursive call, you do not need the loop, and vice versa.
You can either do it recursively:
def sum_digit(n):
if n > 0:
return sum_digit(n // 10) + n % 10
else:
return 0
Or in an iterative way:
def sum_digit(n):
s = 0
while n > 0:
s += n % 10
n //= 10
return s
Or just using bultin functions (probably not what your teacher wants to see):
def sum_digit(n):
return sum(map(int, str(n)))
i must change the while with a if, and it works,thanks for your comments and sorry for posting such a question here.
This will do the trick:
def sum_digit(n, current_sum=0):
if n == 0:
return current_sum
else:
digit = n % 10
current_sum += digit
n //= 10
return sum_digit(n, current_sum)
The output:
print(sum_digit(67154))
> 23
You were mixing up an iterative method (the while loop) and the recursive method (the function call).
In a recursive function, must make sure you get these things right:
The end condition (in our case, we return the sum when the digit is 0)
and
The recursive call (in our case, going down one digit each time)
Change your code as following:
def sum_digit(n):
sum=0
a = n % 10
n //= 10
sum += a
if n > 0 :
sum = sum + sum_digit(n)
return sum
The reason is n is assigned new reference inside function, but it's invisible outside. so while part is loop died. In fact, while part is executed at most once, so code was changed as above.

Factorial in Python using while

why this function doesn't work as a factorial function?
def Factor(n):
while n>=1:
print n*(n-1)
return 1
This will work
def Factor(n):
val=1
while n>=1:
val = val * n
n = n-1
return val
You have recursion and iteration mixed. Take a look at these two:
def factor_recursion(n):
while n>=1:
return n * factor_recursion(n-1)
return 1
def factor_iteration_for(n):
factor = 1
for i in range(n):
factor *= i+1
return factor
def factor_iteration_while(n):
factor = 1
while n >= 1:
factor *= n
n -= 1
return factor
print factor_iteration_for(4)
print factor_iteration_while(4)
print factor_recursion(4)
You never change the value of n to anything other than what is passed into the function.
I don't think this is going to do what you think it will. Looks like you've mixed recursion and iteration.
First of all, none of your code changes the value of n, so the loop will run indefinitely unless n == 1 when the function is called.
Secondly, you aren't accumulating a partial product inside the loop (hint: before the loop set result =, then inside it multiply the current value of result by the value of n.
Finally, you should then return the accumulated result rather than one.
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)
print factorial(5)

Categories

Resources