How to write the Fibonacci Sequence?

前端 未结 30 2386
醉酒成梦
醉酒成梦 2020-11-22 00:32

I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1

30条回答
  •  走了就别回头了
    2020-11-22 01:07

    Just for fun, in Python 3.8+ you can use an assignment expression (aka the walrus operator) in a list comprehension, e.g.:

    >>> a, b = 0, 1
    >>> [a, b] + [b := a + (a := b) for _ in range(8)]  # first 10 Fibonacci numbers
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
    

    An assignment expression allows you to assign a value to a variable and return it in the same expression. Therefore, the expression

    b := a + (a := b)
    

    is equivalent to executing

    a, b = b, a + b
    

    and returning the value of b.

提交回复
热议问题