1

I am currently working on recursion in Python but even though my process is correct I do not get my output format as I wanted.

def fibonacci(n):
if n <= 2:
    return 1
else:
    return fibonacci(n-1) + fibonacci(n-2)

def fibseries(N):
    if N <= 1:
        return []
    return [fibseries(N-1),fibonacci(N-1)]
a = fibseries(5)
print a

This gives me the output :

[[[[[0], 1], 1], 2], 3]

but I want to get:

[0, 1, 1, 2, 3]

I need to understand the thinking process.

3
  • 1
    have you seen stackoverflow.com/questions/494594/… possible duplicate Commented Dec 17, 2016 at 21:03
  • It looks like you are returning an array each tim, hence the nesting Commented Dec 17, 2016 at 22:35
  • Check out pythontutor.com Commented Dec 18, 2016 at 1:03

2 Answers 2

1

The problem is that fibseries returns a list and within fibseries you do:

return [fibseries(N-1),fibonacci(N-1)]

you should concatenate the fibonacci output:

return fibseries(N-1) + [fibonacci(N-1)]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much now I understand my mistake and I can get my result in the given format!
0

The problem is in the line return [fibseries(N-1),fibonacci(N-1)]. Each time you call fibseries, it returns a list so this line creates a new list with two elements, the first of which is itself a list. To get it to do what you want replace that line with return [*fibseries(N-1),fibonacci(N-1)]. The star will expand the first list and add the elements separately.c

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.