【发布时间】:2022-01-23 14:45:36
【问题描述】:
我正在尝试类似的事情:4 Digit Guessing Game Python。变化不大。
程序会生成 999 到 10000 之间的随机数。用户每次尝试失败后都会得到他在正确位置猜到了多少个数字,以及他猜对了多少个数字但没有正确猜到位置。 等等,一个随机数是 3691,用户猜测是 3619。他得到 2 个在正确位置(3 和 6)的数字,还有 2 个正确但在错误位置(1 和 9)的数字。
对于他没有猜到的数字并且重复猜测直到所有 4 位数字都猜到正确的位置时,没有输出。
我的想法是我们将随机数的数字保存到一个列表中,然后对用户猜测的数字做同样的事情。然后我们比较两个列表的第一项等。combination_list[0] == guess_ist[0],如果正确,我们在计数器上添加 +1,我们称之为correct。
问题是我不知道正确猜测但位置不正确的数字。
import random
combination = random.randint(1000, 9999)
print(combination)
digits_combination, digits_guess= [], []
temp = combination
while temp > 0:
digits_combination.append(temp % 10)
temp //= 10
digits_combination.reverse()
print(digits_combination)
guess= int(input("Your numbers are? "))
while not 999 < pokusaj < 10000:
pokusaj = int(input("Your numbers are? "))
if guess!= combination:
while guess> 0:
digits_guess.append(guess% 10)
guess//= 10
digits_guess.reverse()
if guess == combination:
print("Your combination is correct.")
correct_position= 0
correct= 0
test = digits_combination[:] # I copied the list here
while guess!= combination:
while guess> 0:
digits_guess.append(guess% 10)
guess //= 10
digits_guess.reverse()
if digits_guess[0] == test[0]:
correct_position += 1
【问题讨论】:
-
如果没有数字重复,您可以计算它
if combination_list[i] != guess_list[i] and guest_list[i] in combination_list:。对于重复的数字,它可能取决于您如何定义位置不正确。可以通过`list(str(number))获取列表,然后比较每个字符。
标签: python list while-loop