I am trying to make a lottery program for my school (we have an economic system).
My program generates numbers and saves it off into a text file. When I want to "pull" numbers out of my generator I want it to ensure that there is a winner.
Q: How do I have Python select a random line out of my text file and give my output as that number?
Although most of the approaches given here would work, but they tend to load the whole file in the memory at once. But not this approach. So even if the files are big, this would work.
The approach is not very intuitive at first glance. The theorem behind this states that when we have seen N lines in there is a probability of exactly 1/N that each of them is selected so far.
From Page no 123 of 'Python Cookbook'
If the file is very large - you could seek to a random location in the file given the file size and then get the next full line:
another approach:
Distribution:
I don't see the skewnes but perhaps the dataset is too small...
Assuming the file is relatively small, the following is perhaps the easiest way to do it:
With a slight modification to your input file (store the number of items in the first line), you can choose a number uniformly without having to read the entire file into memory first.
Say you have 100 numbers. The probability of choosing the first number is 1/100. The probability of choosing the second number is (99/100)(1/99) = 1/100. The probability of choosing the third number is (99/100)(98/99)(1/98) = 1/100. I'll skip the formal proof, but the odds of choosing any of the 100 numbers is 1/100.
It's not strictly necessary to store the count in the first line, but it saves you the trouble of having to read the entire file just to count the lines. Either way, you don't need to store the entire file in memory to choose any single line with equal probability.
I saw a python tutorials and found this snippet: