Created
January 29, 2013 21:10
-
-
Save StevenClontz/4667906 to your computer and use it in GitHub Desktop.
Choose random line of input while storing only one line at a time and an integer with uniform probability.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# only variables I'm allowed to store/modify | |
i = 0 | |
stored_string = "No input given!" | |
# we'll need to be able to make random choices | |
import random | |
# solution | |
while True: | |
try: | |
i += 1 # count the place of this string/person in line | |
if 1 == random.randint(1,i): | |
# make a decision to keep it with probability 1/i | |
# note for first person, i=1, so this passes | |
stored_string = raw_input() | |
else: | |
# otherwise ignore it | |
raw_input() | |
except EOFError: # ran out of people in line, we're done | |
break | |
# Claim: the line stored had equal probability of being chosen with any other line | |
print "Result:\n%s" % stored_string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment