Last active
August 29, 2015 14:05
-
-
Save mminneman1/750d692f0df2d9f2aa50 to your computer and use it in GitHub Desktop.
Bulls and Cows
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
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