Skip to content

Instantly share code, notes, and snippets.

@StevenClontz
Created January 29, 2013 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StevenClontz/4667906 to your computer and use it in GitHub Desktop.
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.
# 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