Home python Calculation of the Fibonacci Number List Recursion

Calculation of the Fibonacci Number List Recursion

Author

Date

Category

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%

  1. Each recursive call you reset the list of S = [] .
  2. .

  3. 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]

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions