Skip to content

Instantly share code, notes, and snippets.

@mminneman1
Last active August 29, 2015 14:05
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 mminneman1/750d692f0df2d9f2aa50 to your computer and use it in GitHub Desktop.
Save mminneman1/750d692f0df2d9f2aa50 to your computer and use it in GitHub Desktop.
Bulls and Cows
import random
# create 4-digit secret code
secret_code = []
avail_digits = [x for x in range(10)]
for i in range(4):
secret_code.append(avail_digits.pop(random.randint(0,len(avail_digits)-1)))
#collect user input
while True:
# get user guess
raw_guess = input("What do you think my secret code is [Enter 4-digit number]? ")
# validate input
if raw_guess.isdigit() and len(raw_guess) == 4:
break
else:
print("Your guess must be a 4-digit number. Try again\n")
#stage input
guess_list, guess = ([], {})
for i in range(len(raw_guess)):
guess_list.append(int(raw_guess[i]))
guess[guess_list[i]] = {'bull': False, 'cow':False}
#has user figured out the secret code?
if guess_list == secret_code:
print("You Win!")
raise SystemExit
#no - process the guess
#check for bulls and cows
for i in range(len(secret_code)):
if guess_list[i] == secret_code[i]:
guess[guess_list[i]]['bull'] = True #bull - both digit and position are correct
elif secret_code.count(guess_list[i]):
guess[guess_list[i]]['cow'] = True #cow - digit is correct but not position
#accumulate bull/cow counts
cntf = lambda x: sum(1 if guess[i][x] else 0 for i in guess_list)
bullcnt = cntf('bull')
cowcnt = cntf('cow')
#display results
print("You have %i bull%s and %i cow%s" % (bullcnt, bullcnt!=1 and 's' or '', cowcnt, cowcnt!=1 and 's' or ''))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment