I\'m a beginner to Python programming and have come upon an issue with my current assignment. The assignment reads as follows...
Here is an example that uses some more advance python idioms to improve readability and succinctness. This also makes it easier to make a more general solution such as for n digit answers for m base.
import random
from itertools import permutations # for "lucky guess" Easter egg
def main(base=10, size=4):
print 'New game started.\nGood luck!\n'
answer, turn = list(genAnswer(range(base), size)), 1
while True:
hint = ['X' if a == g
else '0' if g in answer
else '-' for a, g in zip(answer, guess(base, size))]
if set(hint) == set(['X']):
if turn == 1:
choices = len(list(permutations(range(base), size)))
print 'You won, lucky guess out of %d possible choices' % choices
else:
print 'Congratulations, you won in %d turns!' % turn
return
print ' Hint %d: %s' % (turn, ''.join(hint))
turn += 1
def genAnswer(digits, size):
'''Python generator function'''
for i in range(size):
choice = random.choice(digits)
yield str(choice)
digits.remove(choice)
def guess(base, size):
'''Uses duck typing for error detection'''
while True:
guess = raw_input('>> Guess: ').strip()
try:
if int(guess, base) < base**size and len(set(guess)) == size:
return guess
except ValueError:
pass
print 'Enter %d unique digits from 0 to %d' % (size, base -1)
>>> main(6, 4)
New game started.
Good luck!
>> Guess: 1234
Hint 1: 0-X-
>> Guess: 12345
Enter 4 unique digits from 0 to 5
>> Guess: 01227
Enter 4 unique digits from 0 to 5
>> Guess: 0123
Hint 2: XX-0
>> Guess: 0135
Congratulations, you won in 3 turns!