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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With