Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Mastermind program
- import random
- # Create a random number of 4 digits between 1 and 6
- masterNumber = [random.randint(1,6) for r in range(4)]
- # User gets 20 guesses
- guesscount=20
- numposition=0
- #Loop through until the 4 numbers are guessed or the 20 guesses are exhausted
- while guesscount>0 and numposition<4:
- print "You have {} guesses left".format(guesscount)
- # Get input and validate that it's in the proper range
- guess = raw_input("Guess my 4 digit number (digits between 1 and 6): ")
- while len([x for x in guess if x not in ("1","2","3","4","5","6")]) > 0:
- guess = raw_input("Invalid guess. Try again: ")
- # Convert input to integers
- guess = [int(x) for x in guess]
- # Find out the number of matches regardless of position. Using a copy of the master number, figure
- # out the number of correct guesses by looping through while popping correct matches. If our master
- # number could never repeat numbers, this would be as simple as len(set(masterNumber) - set(guess))
- # or len([x for x in masterNumber if x in guess])
- right=[]
- numbercopy = masterNumber[:]
- for x in range(4):
- if guess[x] in numbercopy:
- right.append(numbercopy.pop(numbercopy.index(guess[x])))
- numright = len(right)
- # Now find out the number of matches at the right position. Simple list comprehension for this one
- numposition = len([x for x in range(4) if guess[x]==masterNumber[x]])
- # Print out the information and decrement the guess counter
- print "You have {} digits correct and {} in the right position.".format(numright,numposition)
- print
- guesscount -=1
- if numposition==4:
- print "CORRECT! The number was",masterNumber
- else:
- print "You ran out of guesses. The number was",masterNumber
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement