through recursion Calculate the number of fibonacci.
I want to return the list of Fibonacci numbers n
, but as a result I get a mistake:
TypeRorror: CAN Only Concatenate List (not "int") to list
code:
def file (n):
s = []
IF N In (1, 2):
Return 1.
ELSE:
S.APPEND (FIB (N-1) + FIB (N-2))
Return S.
I do not understand why it happens. Thanks in advance for the help.
Answer 1, Authority 100%
def file (n):
IF N In (1, 2):
Return 1.
Return FIB (N - 1) + FIB (N - 2)
Print (FIB (5))
Answer 2, Authority 100%
- Each recursive call you reset the list of
S = []
. - In the base case, you return the number, and should list (from here and error ).
.
Based on this, and the generation of a new number will look different.
Example:
def file (n: int) - & gt; List:
IF n == 1:
Return [1]
ELIF N == 2:
Return [1, 1]
Li = FIB (N-1)
Li.APPEND (Li [-1] + Li [-2])
Return Li.
Print (FIB (5))
stdout
[1, 1, 2nd, 3, 5]