类型错误:必须是str,而不是int;Python

时间:2021-05-10 17:06:38

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

我一直在尝试用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)

类型错误:必须是str,而不是在第17行- memo = [None] * (n + 1)

I can't seem to understand the issue here.

我似乎不能理解这里的问题。

1 个解决方案

#1


2  

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

您需要使用这个t = int(输入(“number”))或print(fib_memo(int(t))))。因为,使用input()的键盘输入是默认字符串。

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)))

#1


2  

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

您需要使用这个t = int(输入(“number”))或print(fib_memo(int(t))))。因为,使用input()的键盘输入是默认字符串。

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)))