I'm still a beginner when it comes to Python. I've most recently attempted the 2nd Project Euler question regarding fibonacci numbers, and unfortunately I am stuck. On a simple for-loop, no less. Within this for-loop I attempt to assign the returned result of a function to a variable, and whether or not said variable matches a condition, a total is increased. However, this loop only runs once before it exits, and I am absolutely perplexed. I'm at the end of my wits; if any of you can help to correct this issue I would be grateful. Below is the relevant portion of my code:
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
x = n - 1
y = n - 2
return x + y
num = input("Input your number of choice: ")
total = 0
The problem area:
for i in range(int(num)):
val = fibonacci(i)
if (val % 2 == 0):
total = total + val
print(total)
Yes, it will only calculate total = total + val
once, when val = 0
, for all other cases, your fibonacci function is returning 2*n -3
which is always odd number, but you are checking if the returned val is even
(which it would never be except for when 0) , and hence the issue.
Maybe you wanted to return something like -
return fibonacci(x) + fibonacci(y) # or the simpler , fibonacci(n-1) + fibonacci(n-2)
Note that the sequence Fn
of Fibonacci numbers is defined by the recurrence relation F_n = F_{n-1} + F_{n-2}
.
Option 1: Using recursion
Instead of return (n-1) + (n-2)
, it should be return fibonacci(n-1) + fibonacci(n-2)
.
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
x = fibonacci(n-1)
y = fibonacci(n-2)
return x + y
num = input("Input your number of choice: ")
print(fibonacci(num))
Here is an example:
$ python fibonacci.py
Input your number of choice: 11
89
Option 2: Using loop
def fibonacci(num):
a,b = 1,1
for i in range(num-1):
a,b = b,a+b
return a
print fibonacci(num)
The issue I see is you are trying to print a variable that was assigned in a for
loop. Instead, you can do...
for i in range(int(num)):
val = fibonacci(i)
if (val % 2 == 0):
return (total + val)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.