我是Python编程的初学者,并且遇到了我当前任务的问题。作业内容如下......
现在我只关注作业的“反馈”部分。我的代码目前是:
import random
def validateInput():
inputGuess = input("Enter your guess as 4 numbers:")
while True:
if len(inputGuess) != 4:
inputGuess = input("Enter your guess as 4 numbers:")
else:
numberList = list(inputGuess) ##
invalidNumbers = False
for number in numberList:
if number not in ['1','2','3','4','5','6','7','8','9']:
invalidNumbers = True
if invalidNumbers == True:
print ("Possible numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9.")
inputGuess = input("Enter your guess as 4 numbers:")
else:
return numberList
guessesRemaining=10
code=['1','2','3','4']
while guessesRemaining > 0:
report=[]
guess=validateInput()
guessesRemaining -= 1
if guess[0] == code[0]:
report.append("X")
if guess[1] == code[1]:
report.append("X")
if guess[2] == code[2]:
report.append("X")
if guess[3] == code[3]:
report.append("X")
tempCode=sorted(code)
tempGuess=sorted(guess)
if tempCode[0]==tempGuess[0]:
report.append("O")
if tempCode[1]==tempGuess[1]:
report.append("O")
if tempCode[2]==tempGuess[2]:
report.append("O")
if tempCode[3]==tempGuess[3]:
report.append("O")
report2=report[0:4]
dash=["-","-","-","-"]
report3=report2+dash
report4=report3[0:5]
print(report4)
例如,如果用户猜测1879并且代码是1234,我收到“X O - ”但我想收到“X ---”。此外,任何关于简化我的代码的建议都会很棒。为简单起见,我现在只做[1,2,3,4]的“随机代码”。
答案 0 :(得分:4)
您可以使用Python函数map()非常优雅地解决您的问题。 (不像我原先想象的那么优雅,但仍然相当不错。)
guess = "1879" # or [ '1', '8', '7', '9' ]
answer = "1234"
map()的工作原理如下:你给它一个函数作为它的第一个参数,并将一个或多个序列作为参数。然后接受该函数并将其首先应用于第一个元素,然后应用于第二个元素,依此类推。例如:
>>> def f(a,b):
>>> return a + b
>>> map( f, [1,2,3,4], [ 10, 20, 30, 40 ] )
[ 11, 22, 33, 44 ]
现在,您有两个字符序列,“猜测”和“答案”。如果它们相等,你可以编写一个返回X的函数 - 否则就像这样:
>>> def mastermind_hint( a, b ):
>>> return "X" if a == b else "-"
这还不够,你还需要加入'O'。为此,您需要立即使用整个“答案”序列:
>>> def mastermind_hint( a, b ):
>>> if a == b: return "X"
>>> if a in answer: return "O"
>>> return "-"
使用map,我们可以将其应用于您拥有的序列:
>>> map( mastermind_hint, guess, answer )
[ "X", "-", "-", "-" ]
现在,我们现在提供的信息比我们预期的要多,因为我们提示的位置对应于猜测字符的位置。隐藏此信息的一种简单方法是对序列进行排序。 Python有一个sorted()函数可以做到这一点:
>>> sorted( map( mastermind_hint, guess, answer ) )
[ "-", "-", "-", "X" ]
剩下的就是将其加入一个字符串:
>>> "".join( sorted( map( mastermind_hint, guess, answer ) ) )
"---X"
答案 1 :(得分:2)
我必须说非常有趣的作业。我希望我能像这样做作业。
通常我没有提供完整的家庭作业答案,但我解决了这个问题很有趣,你试图自己解决这个问题,所以你去了:
import random
def main():
print '>> New game started.\n>> Good luck!\n'
answer = generateAnswer()
while True:
userGuess = getUserGuess()
if userGuess == answer:
print '>> Congratulations, you won!'
return
print '>> The answer you provided is incorrect.\n>> Perhaps this hint will help you: '
giveFeedback(answer, userGuess)
def generateAnswer():
digits = [str(x) for x in range(10)]
answer = ''
for i in range(4):
digit = random.sample(digits, 1)[0]
digits.remove(digit)
answer += digit
return answer
def getUserGuess():
while True:
guess = raw_input('>> Please enter a 4-digit number: ').strip()
if len(guess) != 4:
continue
guessIsValid = True
for x in guess:
if guess.count(x) != 1 or ord(x) not in range(48, 58):
guessIsValid = False
break
if guessIsValid:
return guess
def giveFeedback(answer, guess):
for i in range(4):
if guess[i] == answer[i]:
print 'X',
continue
if guess[i] in answer:
print 'O',
continue
print '-',
print '\n'
if __name__ == '__main__':
try:
main()
except Exception, e:
print '>> Fatal error: %s' % e
我希望你能在这段代码中找到答案。
答案 2 :(得分:1)
这是一个使用一些更高级的python习语来提高可读性和简洁性的例子。这也使得更容易制作更通用的解决方案,例如m base的n位数答案。
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!