Can you infer a Fibonacci sequence with one variable?

Hey, I'm trying to get a Fibonacci sequence for output with one variable in the mix. usually, if I used 2 variables, I would set it like this:

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

but how would I be able to complete it with a single variable in python?

+4
source share
4 answers

Since no one mentioned which object should be a variable, it is used here 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 mean-spirited, you can use the closed-end solution for the Fibonacci series to approximate the gold 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

- n - F[n] . fib.

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

print fib(12) # the 12th fibinocci number

... , , , ,

+3

. memoization .

import functools

@functools.lru_cache(None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

def fib_yield(n):
    for i in range(n):
        yield fib(i)

list(fib_yield(10))  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
+2

, , @joran-beasley

- Memoization, . , .

SO fooobar.com/questions/218396/...

+1

Source: https://habr.com/ru/post/1692822/


All Articles