0
def fib2(n): #return Fibonacci series up to n
     """Return a list containing the Fibonacci series up to n."""
     result = []
     a, b = 0, 1
     while b < n:
          result.append(b) #see below
          a, b = b, a+b
     return result

#===========================================
f35 = fib2(35)     #call it
print (f35)        #write the result

Okay so that's what I have so far. That gives the output [1, 1, 2, 3, 5, 8, 13, 21, 34]. Which is fine, but I need it reversed. Showing [34, 21, 13, 8, 5, 3, 2, 1, 1]. I just can't figure out how to apply the reversed command or use the [::-1] method.

I keep getting a bunch of errors if I try to apply any of the above methods. I'm pretty new at this. Thank you for your time.

Perkle
  • 1
  • 3
    Doesn't `[1, 1, 2, 3, 5, 8, 13, 21, 34][::-1]` give you `[34, 21, 13, 8, 5, 3, 2, 1, 1]` ? – Zero Apr 21 '15 at 08:28

3 Answers3

0

Try this

print (f35[::-1]) // Reversed list will be printed  

There are some other ways around to reverse the list. All of them will work.

You can also use reverse method of list object

f35.reverse()
print(f35)
Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
0

You can use any of this

return result[::-1] # or list(reversed(result))

OR

f35 = fib2(35)
f35.reverse()
print(f35)
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
0

As an alternative, you could use insert instead of append to just build the list in the right order in the first place?

So instead of:

result.append(b)

Do:

result.insert(0, b)

That puts b at index 0 in the list and shoves all the other elements up one.

LexyStardust
  • 1,018
  • 5
  • 18