'How to write a one-liner generator expression for an infinite stream of odd numbers from 1 to 99?
I am trying to write a one-liner Python generator expression that provides an infinite stream of odd random numbers between 1 and 99 inclusively.
Can anyone please help me?
Solution 1:[1]
import random as rdm
g = (1+2*rdm.randint(0, 49) for r in iter(int, 1))
rdm.randint(0, 49)
gives you a random int between 0 and 49. So (1+2*rdm.randint(0, 49)
gives you a random number odd number between 1 and 99.
iter(int, 1)
is an infinite iterator (which is always 0 and just used to keep the generator going).
Solution 2:[2]
You can use itertools.count()
to make infinite loop and itertools.filterfalse
to filter values you don't need:
from random import randint
from itertools import count, filterfalse
f = filterfalse(lambda i: i % 2 == 0, [(yield randint(1, 99)) for i in count()])
for i in f:
print(i)
Prints:
...
61
21
91
77
39
... and so on
Version 2 (without itertools):
from random import randint
for val in (i for i in iter(lambda: randint(1, 99), 0) if i % 2 != 0):
print(val)
Solution 3:[3]
Do this: (Python 3)
stream = (lambda min_, max_: type("randint_stream", (), {'__next__': (lambda self: 1+2*__import__('random').randint(min_-1,max_//2))}))(1,99)()
Get randint with next(stream)
.
Change min and max by changing the (1,99)
.
Real 1 line! Can change min & max!
=========== Adding ===========
The version above isn't a strict generator -- it's another class. Version 2:
stream = (lambda min_, max_: (1+2*__import__('random').randint(min_-1,max_//2) for x in iter(int, 1)))(1,99)
Use next()
to get random odd number.
Change min and max by changing the (1,99)
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Raphael |
Solution 2 | |
Solution 3 |