首页 > 解决方案 > 作业遇到问题

问题描述

我正在为学校做作业,我需要制作一个列表并将 4 个随机整数分配给 1 到 9 之间的列表。然后,我需要提示用户他们对每个值的猜测是什么。如果他们得到任何正确的数字,我需要说出有多少,但我已经为此工作了大约 3 个小时,但我一无所获。目前,我所拥有的只是大量无用的嵌套 if/elif 语句。这是作业提示:

节目规格:

计算机应生成 1 - 9 的 4 个随机数作为“密码”。应该提示用户猜测这四个数字。在他们提供完整的猜测之后,用户会被告知有多少是正确的。只要用户没有得到所有四个正确,他们就会不断被要求猜测。在用户最终全部正确后(是的 - 所有四个),他们会受到祝贺,然后告诉他们尝试了多少次。技术要求:

使用至少一个列表 使用至少一个带参数的函数

我很困惑,我不知道从哪里开始。这是我当前的代码:

import random

count = 0
guess1 = 1
guess2 = 1
guess3 = 1
guess4 = 1

def getGuess(count,guess1,guess2,guess3,guess4):
  while True:
    guess1 = input("What is your guess for the first number? ")
    guess2 = input("What is your guess for the second number? ")
    guess3 = input("What is your guess for the third number? ")
    guess4 = input("What is your guess for the fourth number? ")
    if str(guess1) == numbers[0] and str(guess2) == numbers[1] and str(guess3) == numbers[2] and str(guess4) == numbers[3]:
      print("Your first, second, third, and fourth numbers are correct!")
    elif guess1 == numbers[0] and guess2 == numbers[1] and guess3 == numbers[2]:
      print("Your first, second, and third numbers are correct!")
    elif guess1 == numbers[0] and guess2 == numbers[1]:
      print("Your first and second number are correct!")
    elif guess1 == numbers[0]:
      print("Your first number is correct!")
    elif guess2 == numbers[1]:
      print("Your second number is correct!")
    elif guess2 == numbers[1] and guess3 == numbers[2]:
      print("Your second and third numbers are correct!")
    elif guess2 == numbers[1] and guess3 == numbers[2] and guess4 == numbers[3]:
      print("Your second, third, and fourth numbers are correct!")
    elif guess3 == numbers[2]:
      print("Your third number is correct!")
    elif guess3 == numbers[2] and guess4 == numbers[3]:
      print("Your third and fourth numbers are correct!")
    elif guess4 == numbers[3]:
      print("Your fourth number is correct!")
    else:
      print("None of your numbers are correct. Try again.")
      
numbers = []

for i in range(4):
  num = int(random.randrange(1,9))
  numbers.append(num)

print(numbers)

getGuess(count,guess1,guess2,guess3,guess4)

标签: pythonpython-3.x

解决方案


您可以优化代码的许多部分。

假设:您知道如何使用列表,因为您已经将numbers其用作列表。我远离字典。不知道你是否知道它的用途。还假设您了解列表理解。如果您不这样做,请参阅列表理解上的此链接。

现在让我们看看你的代码。这里有几点需要考虑:

  1. 您不需要 4 个变量来存储 4 个输入值。您可以使用一个列表并将所有 4 个都存储在那里。

  2. 正如许多人已经建议的那样,您应该将输入值转换为整数。当您将字符串转换为整数时,字符串可能不是整数。这可能会导致代码被破坏。所以在转换为 int 时使用 Try except 来捕获错误

  3. 您的 random.randrange(1,9) 将创建整数。所以你不必显式地将它们转换回整数。

  4. 您有 4 个输入和 4 个值要比较。您可以将每个值映射到位置并进行比较。这将降低复杂性。对于那些成功的,请保留它的标签。然后打印匹配的。同样,这可以使用列表或字典来完成。

考虑到所有这些,我重新编写了您的代码,如下所示。看看这是否可以帮助您解决问题。

import random

nums = [random.randrange(1,9) for _ in range(4)]

def getGuess():
    g = ['first','second','third','fourth']
    i = 0
    gx = []
    while i<4:
        try:
            x = int(input(f"What is your guess for the {g[i]} number? :"))
            gx.append(x)
            i+=1
        except:
            print ('Not numeric, please re-enter')
    
    gwords = [g[i] for i in range(4) if nums[i] == gx[i]]
   
    if gwords:
        if len(gwords) == 1:
            resp = "Your " + gwords[0] + ' number is correct!'
        else:
            resp = "Your " + ', '.join(gwords[:-1]) + ' and ' + gwords[-1] + ' numbers are correct!'
        print (resp)
    else:
        print ("None of your numbers are correct. Try again.")
    

getGuess()

这是上述代码的示例运行:

What is your guess for the first number? :1
What is your guess for the second number? :6
What is your guess for the third number? :5
What is your guess for the fourth number? :4
Your second, third and fourth numbers are correct!

推荐阅读