0

I am trying to implement a fibonacci function that should takes as input 3 arguments, r = the number of the output elements, 'a' the start number and 'b' the second number. fib(r,a,b)

I have done the following but something goes wrong:

def fib(r,a,b):
    return [[(a,b),fib(i,b,a+b)] for i in range(r)]

Can anyone said me where is the problem and help me to solve it?

12
  • 3
    What goes wrong? Is it hanging? Syntax error? Commented Oct 27, 2015 at 23:11
  • Side note: if this is python 2 range(SOME_BIG_NUMBER) will actually create a list with many numbers inside before doing anything. Commented Oct 27, 2015 at 23:12
  • What is the desired output? As it is, even if you fix the errors, you will get lists inside lists Commented Oct 27, 2015 at 23:15
  • the function is called fib and inside it calls fib (refers to itself) Commented Oct 27, 2015 at 23:15
  • 2
    Please change your question containing the desired and the actual output. Putting that in comments is not such a good idea. Commented Oct 27, 2015 at 23:17

1 Answer 1

2

You're calling the function within the list comprehension, making the lists recursive. Also, you're missing a condition under which the function terminates.

Try this instead:

def fib(r,a,b):
    return [a] + fib(r-1,b,a+b) if r>0 else []

Note that this is horribly inefficient and should never be actually used.

Sign up to request clarification or add additional context in comments.

2 Comments

ok i have understand, but i cant to do it like this because i can concatenate list with list not number with list. is it right?
Correct, that's why you concatenate a list with a list here! a is a number, but [a] is a list!

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.