Python Fibonacci Generator Program Error

gulshan212

New member
Hello this is Gulshan Negi
I am creating a program for generating Fibonacci sequences, but there is a problem in execution, I don't know what I am doing wrong here.
source code:

fib_cache = {}


def fib_memo(input_val):
if input_val in fib_cache:
return fib_cache[input_val]

if input_val == 0:
val = 0
elif input_val < 2:
val = 1
else:
val = fib_memo(input_val - 1) + fib_memo(input_val - 2)

fib_cache[input_val] = val
return value


if __name__ == __main__:
print('======== Fibonacci Series ========')
for i in range(1, 11):
print(f'Fibonacci ({i}) : {fib_memo(i)}')

I also take references from here, but I don't know what I am doing wrong here. What do you think about it?
 

Kate

Administrator
Команда форума
Hello this is Gulshan Negi
I am creating a program for generating Fibonacci sequences, but there is a problem in execution, I don't know what I am doing wrong here.
source code:

fib_cache = {}


def fib_memo(input_val):
if input_val in fib_cache:
return fib_cache[input_val]

if input_val == 0:
val = 0
elif input_val < 2:
val = 1
else:
val = fib_memo(input_val - 1) + fib_memo(input_val - 2)

fib_cache[input_val] = val
return value


if __name__ == __main__:
print('======== Fibonacci Series ========')
for i in range(1, 11):
print(f'Fibonacci ({i}) : {fib_memo(i)}')

I also take references from here, but I don't know what I am doing wrong here. What do you think about it?

I noticed a few issues in your code that may be causing the problem:

  1. There is a typo in the return statement in the fib_memo function. Instead of returning value, you should be returning val.
  2. The __name__ variable should be a string, so you need to enclose the double underscores in quotes like this: '__main__'.
Here's the corrected code:

Код:
fib_cache = {}

def fib_memo(input_val):
    if input_val in fib_cache:
        return fib_cache[input_val]

    if input_val == 0:
        val = 0
    elif input_val < 2:
        val = 1
    else:
        val = fib_memo(input_val - 1) + fib_memo(input_val - 2)

    fib_cache[input_val] = val
    return val

if __name__ == '__main__':
    print('======== Fibonacci Series ========')
    for i in range(1, 11):
        print(f'Fibonacci ({i}) : {fib_memo(i)}')

This code should generate the Fibonacci sequence correctly for the range 1 to 10.
 
Сверху