0

I've been trying to write a code for Fibonacci using memorization on Python.

Here's my code

def fib(n, memo):
    if memo[n] is not None:
        return memo[n]
    if n == 1 or n == 2:
        result = 1
    else:
        result = fib_2(n-1, memo) + fib_2(n-2, memo)

memo[n] = result
return result

def fib_memo(n):
    memo = [None] * (n + 1)
    return fib(n, memo)

t = input("number ")

print(fib_memo(t))

It returns:-

TypeError: must be str, not int" on line 17- memo = [None] * (n + 1)

I can't seem to understand the issue here.

2
  • 4
    you need to use this t = int(input("number")) or print(fib_memo(int(t))). Because, keyboard input using input() are by default string. Commented Mar 19, 2018 at 9:43
  • 3
    Input returns a string, not an integer. You need to do t = int(input("...")) Commented Mar 19, 2018 at 9:44

1 Answer 1

1

You need to use this t = int(input("number")) or print(fib_memo(int(t))). Because, keyboard input using input() are by default string.

Here's your complete working code:-

def fib(n, memo):
    if memo[n] is not None:
        return memo[n]
    if n == 1 or n == 2:
        result = 1
    else:
        result = fib(n-1, memo) + fib(n-2, memo)

    memo[n] = result
    return result

def fib_memo(n):
    memo = [None] * (n + 1)
    return fib(n, memo)

t = input("number ")

print(fib_memo(int(t)))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.