I have the following exercise:
"Write a recursive function that prints the n-th number of the fibonacci sequence. The function parameters are 'n','current_number' [F(0)] and 'next_number' [F(1)]. [F(0)] and [F(1)] are the initial seeds of the sequence. Write the main program that ask user for the input parameters. Your code must output the result as follows.
fibon({n},{current_number},{next_number}) = {result}
fibon(5,4,5) = 37
fibon(5,0,1) = 5
fibon(10,0,1) = 55
The following solution seems to work
def fibon(n, current_number, next_number):
#print(f'n is {n} from the outset')
if n == 0:
#print('n == 0 is true')
return current_number
elif n == 1:
#print('n == 1 is true')
return next_number
else:
n = n-1
#print(f'this is n-1 {fibon(n-1, current_number, next_number)}')
#print(f'this is n {fibon(n, current_number, next_number)}')
fib= fibon(n-1, current_number, next_number) + fibon(n, current_number, next_number)
#print(fib)
return(fib)
However, I don't understand how 'fibon' is returning the value of nth number in fibonacci series. It is a recursive function and I don't understand how every time it loops, it gets the fibonacci number for the nth position. If you look at the code, " fibon(n-1, current_number, next_number) + fibon(n, current_number, next_number)" can only return a number when n== 1 or n==0. If so, how it can reutrn other numbers in the position when they are not in the 1th or 0 position?
I am not sure if I made a lot of sense but I tried to express my confusin. Thanks in advance!
The code is working but I do not seem to understand why it is working. You can also propose a better solution if there is one. Thank you very much!
Related
Recently, I was trying to create an algorithm for finding a square root of a number. I am kind of new to python programming. This is my implementation:
def findSquareRt(num):
n = 8 #Initial Guess
while True:
if n**2 < num:
if not num/n == n:
temp = n
n = num/n
if (int((temp+n)/2))**2 == num:
return ((temp+n)/2)
else:
n = (temp+n)/2
But when i run the above code it just doesn't produce any output. Maybe it is the looping condition which is causing this, but i cant figure that out.
Your code has a lot of issues, one of them being that you will get an infinite loop if n**2 > num.
A simpler way of doing this would be something like this:
def findSquareRt(num):
return num**0.5
Thank you for responding to the question, From responses there were two problems:
first problem:
if n**2 < num:
this condition is always returning False on second or some other future iterations, and is redundant so this should be removed in order to get a solution.
second problem:
if (int((temp+n)/2))**2 == num:
The integer conversion of the expression ((temp+n)/2) is returning floor value of the float numbers, which effects the precision of the output hence the program stuck infinitely in the loop waiting for the condition to be True. Hence needed to be changed.
Final Solution:
def findSquareRt(num):
n = 8 #Initial Guess
while True:
if not num/n == n:
temp = n
n = num/n
if (((temp+n)/2))**2 == num:
return ((temp+n)/2)
else:
n = (temp+n)/2
else:
return n
def fibonacci(n):
for i in range(n,1):
fab=0
if(i>1):
fab=fab+i
i=i-1
return fab
elif i==0:
return 0
else:
return 1
n1 = int(input("enter the nth term: "))
n2=fibonacci(n1)
print(n2)
The only way your code can return none is if you enter an invalid range, where the start value is greater than or equal to the stop value (1)
you probably just need range(n) instead of range(n, 1)
You can do this too:
def fibonacci(n):
return 0 if n == 1 else (1 if n == 2 else (fibonacci(n - 1) + fibonacci(n - 2) if n > 0 else None))
print(fibonacci(12))
You may need to use recursion for for nth Fibonacci number:
ex:
def Fibonacci(n):
if n==1:
return 0
elif n==2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
print(Fibonacci(9))
# output:21
If you do not plan to use large numbers, you can use the easy and simple typical recursive way of programming this function, although it may be slow for big numbers (>25 is noticeable), so take it into account.
def fibonacci(n):
if n<=0:
return 0
if n==1:
return 1
return fibonacci(n-1)+fibonacci(n-2)
You can also add a cache for the numbers you already stepped in, in order to make it run much faster. It will consume a very small amount of extra memory but it allows you to calculate larger numbers instantaneously (you can test it with fibonacci(1000), which is almost the last number you can calculate due to recursion limitation)
cache_fib = {}
def fibonacci(n):
if n<=0:
return 0
if n==1:
return 1
if n in cache_fib.keys():
return cache_fib[n]
result = fibonacci(n-1)+fibonacci(n-2)
cache_fib[n] = result
return result
In case you really need big numbers, you can do this trick to allow more recursion levels:
cache_fib = {1:1}
def fibonacci(n):
if n<=0:
return 0
if n in cache_fib.keys():
return cache_fib[n]
max_cached = max(cache_fib.keys())
if n-max_cached>500:
print("max_cached:", max_cached)
fibonacci(max_cached+500)
result = fibonacci(n-1)+fibonacci(n-2)
cache_fib[n] = result
return result
range(n,1) creates a range starting with n, incrementing in steps of 1 and stopping when n is larger or equal to 1. So, in case n is negative or zero, your loop will be executed. But in case n is 1 or larger, the loop will never be executed and the function just returns None.
If you would like a range going from n downwards to 1, you can use range(n,1,-1) where -1 is the step value. Note that when stepping down, the last number is included range(5,1,-1) is [5,4,3,2,1] while when stepping upwards range(1,5) is [1,2,3,4] the last element is not included. range(n) with only one parameter also exists. It is equivalent to range(0, n) and goes from 0 till n-1, which means the loop would be executed exactly n times.
Also note that you write return in every clause of the if statement. That makes that your function returns its value and interrupts the for loop.
Further, note that you set fab=0 at the start of your for loop. This makes that it is set again and again to 0 each time you do a pass of the loop. Therefore, it is better to put fab=0 just before the start of the loop.
As others have mentioned, even with these changes, your function will not calculate the Fibonacci numbers. A recursive function is a simple though inefficient solution. Some fancy playing with two variables can calculate Fibonacci in a for loop. Another interesting approach is memorization or caching as demonstrated by #Ganathor.
Here is a solution that without recursion and without caching. Note that Fibonacci is a very special case where this works. Recursion and caching are very useful tools for more real world problems.
def fibonacci(n):
a = 0
b = 1
for i in range(n):
a, b = a + b, a # note that a and b get new values simultaneously
return a
print (fibonacci(100000))
And if you want a really, really fast and fancy code:
def fibonacci_fast(n):
a = 1
b = 0
p = 0
q = 1
while n > 0 :
if n % 2 == 0 :
p, q = p*p + q*q, 2*p*q + q*q
n = n // 2
else:
a, b = b*q + a*q + a*p, b*p + a*q
n = n - 1
return b
print (fibonacci_fast(1000000))
Note that this relies on some special properties of the Fibonacci sequence. It also gets slow for Python to do calculations with really large numbers. The millionth Fibonacci number has more than 200,000 digits.
The question: Assume the availability of a function is_prime. Assume a variable n has been associated with positive integer. Write the statements needed to find out how many prime numbers (starting with 2 and going in increasing order with successively higher primes [2,3,5,7,11,13,...]) can be added before exceeding n. Associate this number with the variable k.
The code:
def is_prime():
i = 2
k = 0
Again = True
while Again = True:
if total > n:
Again = False
for x in range(2,n):
if x % i == 0:
total = total
k = k
i += 1
else:
total += x
k += 1
return k
Your code is not correct for an issue involving prime number tracking and consecutive addition. Nor anything else. The obvious issue is that it doesn't run, so it can't be correct. One syntax bug is this:
while Again = True:
which should be:
while Again == True:
Another is that total is never initialized before it's value is used:
total += x
Once we fix those problems, your code still doesn't appear to work. But let's back up a bit. The stated problem says,
Assume the availability of a function is_prime.
But you didn't do that -- you wrote your solution with the name is_prime(). We should expect that there is a function named is_prime(n) and it tests if n is prime or not, returning True or False. You are either given this, need to find one, write one, or simply assume it exists but never actually test your code. But once you have this function, and it works, you shouldn't change it!
Here's my example is_prime(n) function:
def is_prime(n):
""" Assume the availability of a function is_prime. """
if n < 2:
return False
if n % 2 == 0:
return n == 2
for m in range(3, int(n ** 0.5) + 1, 2):
if n % m == 0:
return False
return True
Now write your solution calling this function, but not changing this function. Here's one possible algorithm:
Write a function called primes_in_sum(n)
Set the variable prime to 2 and the variable k (our counter) to
0.
Subtract prime from n.
While n >= 0, increment k, and compute the next value of prime
by keep adding one to prime until is_prime(prime) returns true.
Then again subtract prime from n. Back to the top of this loop.
When the while condition fails, return k.
Test your code works by outputting some values:
for n in range(2, 100):
# Assume a variable n has been associated with a positive integer
print(n, primes_in_sum(n))
Check in your head that the results are reasonable.
I'm solving Euler problem set #2, and I have found the function relevant to what I want I want to do, well partially at least since I'll need to make modifications for even numbers in the fibonacci sequence. I'm trying to print out fibonacci numbers, up to a certain point, n.
def fib(n):
if n == 1:
return 1
elif n == 0:
return 0
else:
return fib(n-1) + fib(n-2)
Giving
>>> fib(13)
233
However
>>> fib(200)
returns nothing. I'm not sure if it is taking long to compute, or whatnot. I might try this in C++, but would like some knowledge from here first.
It's just taking a long time to compute, because you're recursively calling fib() many, many times. If you add a line as follows you can get status update on it as it runs. It'll take a very long time because of the amount of recursion (if it even finishes).
def fib(n):
print("Fibonacci: {0}".format(n))
if n == 1:
return 1
elif n == 0:
return 0
else:
return fib(n-1) + fib(n-2)
I'm trying to calculate the numbers of the fibonacci Sequence under 100, but the code I made doesn't work. What I have is:
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
num=0
while(num<100):
print (fib(num))
num+=1
I think this should work, but it doesn't, so it's definitely my issue with my coding. Could anyone resolve this?
So what about this code is not working? It looks like the implementation is correct, but it's of course, slow. You can try to store the numbers you compute in some kind of data structure as you go along to reduce your stack trace and prevent having to recalculate fib of 23 when you're trying to calculate fib of 24.