【问题标题】:Guess 4 digit combination game猜四位数组合游戏
【发布时间】: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


【解决方案1】:

我有这个解决方案。我建议您转换为字符串,然后转换为列表以获取数字列表,而不是使用 while 循环。对于这个问题,您可以尝试使用“in”关键字来检查数字组合中的数字是否在正确的位置。

import random
combination = random.randint(1000, 9999)
print(combination)

digits_combination = list(str(combination))

guess= int(input("Your numbers are? "))
while not 999 < guess < 10000:
    guess = int(input("Your numbers are? "))

digits_guess = list(str(guess))

if guess == combination:
    print("Your combination is correct.")

correct_position = 0
correct = 0
for index, value in enumerate(digits_guess):
  if value == digits_combination[index]:
    correct_position += 1
  elif value in digits_combination:
    correct += 1

【讨论】:

  • 不需要转换成lists:直接使用字符串即可。此外,您不需要将用户输入转换为int:只需检查"1000" &lt;= guess &lt;= "9999。更重要的是,你如何处理重复的数字?假设组合是“1234”,猜测是“5116”
猜你喜欢
  • 2016-08-16
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2016-06-21
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多