1
fib = [0,1]
a = 1
b = 0
i = 0
while i < n:
   i = a+b
   a,b = i, a
   fib.append(i)

This works in cases where 'n' (which is a given variable) is a number in an actual Fibonacci sequence, like 21 or 13. However, if the number is something like six, it adds one more number than it should. The list should not contain a number that is greater than n.

Jack Bonneman
  • 1,783
  • 17
  • 23

2 Answers2

4

You could always add a to the list first, then do your incrementing.

fib = [0]
a, b = 1, 0
while a <= n:
   fib.append(a)
   a,b = a+b, a
Matt Bryant
  • 4,741
  • 4
  • 30
  • 46
0

Using the classic shnazzy recursive Fibonacci function (which took me a few tries to remember and get right):

def fib(num):
    if ((num == 0) or (num == 1)): return 1
    fib_num = fib(num - 1) + fib(num - 2)
    return fib_num

x, n, i = 2, 15, []
while (fib(x) < n):
    i.append(fib(x))
    x += 1
scohe001
  • 14,655
  • 2
  • 30
  • 50
  • 3
    I think by "self-calling" you mean _recursive_. (It's good to use the right terminology.) Also, recursive Fibonacci is notorious for its exponential complexity... – DaoWen Jul 24 '13 at 02:33
  • +1^ Ahh, I was look for that word. I realize it's pointless to find the whole sequence over and over again for every value like this, but I figure if he's making a script with the Fibonacci sequence he might have some use for it (also it was a good exercise to have to remake it after so long) – scohe001 Jul 24 '13 at 02:36
  • You should provide a memoized version of it. That might at least be useful for him to learn from. – Matt Bryant Jul 24 '13 at 02:43
  • It looks like the one I "made" is the same as some of these (http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python). There were also some other interesting methods in that answer for @user2612750 – scohe001 Jul 24 '13 at 03:03
  • Although you've provided an alternative implementation of the function, you haven't actually answered the question. – Rob Kennedy Jul 24 '13 at 05:18