【问题标题】:Check if userinput matches any digits of a (random) integer检查用户输入是否匹配(随机)整数的任何数字
【发布时间】:2020-10-20 03:40:30
【问题描述】:
random = random.randint(1000, 9999)
guess = int(input("Enter your guess: "))
while guess != random:
    guess = int(input("That was incorrect! Enter your guess: "))

这是一个非常简单的猜谜游戏,但是我想添加一些内容,在每次尝试失败后,它会显示四位数字中有多少数字是正确的。

我没有尝试过,主要是因为我不确定如何做到这一点。

例如

random = 1234
Enter your guess: 1111
You guessed 1 number correct
Enter your guess: 1222
You guessed 2 numbers correct
...... and so on

【问题讨论】:

  • 您可以使用str(number) 将这两个数字转换为字符串,然后逐个字符地遍历它们,并在两者中的字符相同时增加一个计数器变量。

标签: python random integer selection


【解决方案1】:

如果你的意思是职位

random = random.randint(1000, 9999)
guess = int(input("Enter your guess: "))
while guess != random:
    right = 0
    index = 0
    for char in str(guess):
        if char == str(random)[index]:
            index += 1
            right += 1
    print(f'{right} were right')
    guess = int(input("That was incorrect! Enter your guess: "))

【讨论】:

    【解决方案2】:

    如果您真的想将两个数字都保留为 int,您可以使用 %(模运算符)找到整数除以它的基数为 10 的余数。

    例如。

        correctnum = 0
        random = 1234
        guess = 1111
        if ((((random-(random % 1000 )) /1000) == (((guess-(guess % 1000 )) /1000)):
          correctnum++
    

    100/10/1 重复的公式应该都比较该“点”中的数字,而无需转换数据类型。然后输出正确数字的值,你应该有你需要的。

    【讨论】:

      【解决方案3】:
      random = 1234
      random = str(random)
      
      #guess = str(input('enter your guess'))
      guess = '1222'
      correct = 0
      for i in range(len(guess)):
          if guess[i] == random[i]:
              correct += 1
      
      print(correct)
      ouput: 2
      

      或者简单地说:

      correct = sum(guess[i] == random[i] for i in range(len(guess)))
      

      【讨论】:

        猜你喜欢
        • 2014-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 2022-01-02
        • 1970-01-01
        相关资源
        最近更新 更多