Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can you output a Fibonacci sequence with one variable?

Tags:

python

Hey I am trying to get a Fibonacci sequence to output with a single variable in the mix. normally if I was using 2 variables I would have it set up like this:

nmbr1 = nmbr2 = 1
while nmbr1 < 100:
  nmbr1, nmbr2 = nmbr1 + nmbr2, nmbr1
  print (nmbr1)

but how would I get it complete the sequence with only one variable in python?

like image 576
Mast3r_Heath Avatar asked Jan 03 '23 21:01

Mast3r_Heath


2 Answers

Since nobody mentioned what sort of object the variable should be, here's using a list ;-)

x = [1, 1]

while x[0] < 100:
     x = x[1], sum(x)
     print(x[0])

1
2
3
5
8
13
21
34
55
89
144

If you really want to be sneaky, you can use the closed form solution for the Fibonacci series by approximation with the golden ratio.

def fib(n): 
    return int((((1 + 5 ** .5) / 2) ** n) / (5 ** .5) + .5)

f = c = 1
while f < 100:
    c += 1
    f = fib(c) 
    print(f)

1
2
3
5
8
13
21
34
55
89
144

This only uses one variable - n - and it calculates F[n] in constant time. Run a loop and keep calling fib successively.

like image 137
cs95 Avatar answered Jan 05 '23 12:01

cs95


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

print fib(12) # the 12th fibinocci number

maybe ... it works a bit different then yours and it will fall apart with big numbers probably

like image 24
Joran Beasley Avatar answered Jan 05 '23 10:01

Joran Beasley