Issue
I am using Python 3.9 & have a list list1 = ['a', 'b', 'c', 'd']
I want to get a random item from the list without using any module like there is a module random
in Python and a function random.choice(list1)
I can use this but is there another way to get a random item from a list in Python without using any module?
Solution
Random and pseudorandom number generators will ultimately rely on some kind of module, if only to get a seed needed to produce pseudorandom numbers. One common example of a seed is time.time
found in the time
module, though it's not necessarily a good one. The only way without a module is to choose a fixed seed, but then only a fixed sequence of numbers is possible.
Besides the seed, there is the algorithm. One popular choice is the linear congruential generator (LCG). This algorithm is appropriate for learning purposes; however, LCGs are far from perfect and should not be used in security applications or serious simulations. See this answer: How to sync a PRNG between C#/Unity and Python?
There are two more things involved in the solution: generating a uniform random integer, and choosing a uniform random item from a list.
- Generating a uniform random integer in [0, n); that is, building
RNDINTEXC(n)
. For that, see Melissa O'Neill's page. - Choosing a uniform random item from a list, doing
list[RNDINTEXC(len(list))]
.
Answered By - Peter O.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.