treyhunner,
@treyhunner@mastodon.social avatar

Today I wondered whether I could generate Fibonacci numbers in a list comprehension using 's walrus operator.

It turns out that this is possible... and I do not recommend it. 😬🤭

>>> a = b = 1
>>> n = 15
>>> fibonacci = [(old:=a, a:=b, b:=old+b)[0] for _ in range(n)]
>>> fibonacci
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

treyhunner,
@treyhunner@mastodon.social avatar

A generator expression even works 🤯

>>> from itertools import count, islice
>>> fibonacci = ((old:=a, a:=b, b:=old+b)[0] for _ in count())
>>> a = b = 1
>>> print(*islice(fibonacci, 5))
1 1 2 3 5

Note that we defined a & b AFTER making the generator object.

You can even reset a & b to start it all over:

>>> a = b = 1
>>> print(*islice(fibonacci, 7))
1 1 2 3 5 8 13

Or you could decide to switch from Fibonacci to Lucas numbers:

>>> a, b = 2, 1
>>> print(*islice(fibonacci, 7))
2 1 3 4 7 11 18

treyhunner,
@treyhunner@mastodon.social avatar

Yet another way, by putting an assignment expression within an assignment expression:

>>> from itertools import count, islice
>>> a = b = 1
>>> numbers = ((b:=a+(a:=b))-a for _ in count())
>>> list(islice(numbers, 12))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

folkerschamel,
@folkerschamel@mastodon.social avatar

@treyhunner Somebody writing such code I would first complement them for their IQ of 200 and then give them a good talking to: don't pull the hairs of your playmate.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • python
  • tacticalgear
  • DreamBathrooms
  • InstantRegret
  • magazineikmin
  • osvaldo12
  • Youngstown
  • ngwrru68w68
  • slotface
  • everett
  • rosin
  • thenastyranch
  • kavyap
  • GTA5RPClips
  • tester
  • JUstTest
  • modclub
  • cubers
  • ethstaker
  • mdbf
  • khanakhh
  • Durango
  • normalnudes
  • Leos
  • cisconetworking
  • anitta
  • provamag3
  • megavids
  • lostlight
  • All magazines