kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Get all kandi verified functions for this library.
Uniform Dev Icons
Uniform Social Icons
Visitors Counter Badge
GitHub Profile Stats Card
GitHub Top Skills
GitHub Streak Stats
Dynamic Dev(.)to Blogs (GitHub Action)
Dynamic Medium Blogs (GitHub Action)
Dynamic Personal Blogs from RSS Feed (GitHub Action)
Wakatime Stats contribute
Buy Me A Coffee button
How can I make an object with an interface like a random number generator, but that actually generates a specified sequence?Asked 2022-Mar-31 at 13:47
I'd like to construct an object that works like a random number generator, but generates numbers in a specified sequence.
# a random number generator rng = lambda : np.random.randint(2,20)//2 # a non-random number generator def nrng(): numbers = np.arange(1,10.5,0.5) for i in range(len(numbers)): yield numbers[i] for j in range(10): print('random number', rng()) print('non-random number', nrng())
The issue with the code above that I cannot call
nrng in the last line because it is a generator. I know that the most straightforward way to rewrite the code above is to simply loop over the non-random numbers instead of defining the generator. I would prefer getting the example above to work because I am working with a large chunk of code that include a function that accepts a random number generator as an argument, and I would like to add the functionality to pass non-random number sequences without rewriting the entire code.
EDIT: I see some confusion in the comments. I am aware that python's random number generators generate pseudo-random numbers. This post is about replacing a pseudo-random-number generator by a number generator that generates numbers from a non-random, user-specified sequence (e.g., a generator that generates the number sequence
1,1,2,2,1,0,1 if I want it to).
ANSWERAnswered 2022-Mar-29 at 00:47
You can call
next() with a generator or iterator as an argument to withdraw exactly one element from it. Saving the generator to a variable beforehand allows you to do this multiple times.
# make it a generator def _rng(): while True: yield np.random.randint(2,20)//2 # a non-random number generator def _nrng(): numbers = np.arange(1,10.5,0.5) for i in range(len(numbers)): yield numbers[i] rng = _rng() nrng = _nrng() for j in range(10): print('random number', next(rng)) print('non-random number', next(nrng))
No vulnerabilities reported