0
def fib(n):
   if n<= 1: 
       return n 
   else: 
       return(fib(n-1)+fib(n-2))

def comp():
   L=[]
   for i in range(1,4000000): 
        if i % 2 ==0:
           L.append(fib(i))
           return sum(L)
print(comp())

What is wrong with this code? It does not return anything but it looks good according to me.

cavuscanay
  • 27
  • 4
  • fib itself taking more times, optimization of fibonacci will work, you can take example https://www.programiz.com/python-programming/examples/fibonacci-sequence – utks009 Jan 15 '20 at 12:58

2 Answers2

0

The return statement is set to the wrong increment. It is executed the first time i % 2 == 0 becomes true (which is i == 2 in your case).

def fib(n):
   if n<= 1: 
       return n 
   else: 
       return(fib(n-1)+fib(n-2))

def comp():
   L=[]
   for i in range(1,4000000): 
        if i % 2 ==0:
           L.append(fib(i))
   return sum(L)

print(comp())

The above code is not going to work, though. Are you aware of how big this number would get?

Try

for i in range(1,40): 

as a start. It took quite a few seconds on my machine. Result is 63245985.

offeltoffel
  • 2,691
  • 2
  • 21
  • 35
0

you should return sum(L) from function not from for loop follow below code

def fib(n):
    if n<= 1: 
        return n 
    else: 
        return(fib(n-1)+fib(n-2))

def comp():
    L=[]
    for i in range(1,20): 
        if i % 2 ==0:
            L.append(fib(i))
    return sum(L)

print(comp())

and other thing look at the range its too much,because of this it will take some time or may produce any memory related error, so reduce it for testing.

The Guy
  • 411
  • 4
  • 11