为什么在一场牛与牛的比赛中,我总是得到错误的公牛数量?

2024-10-04 11:27:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是Python新手。我正在尝试编写一个奶牛和公牛的游戏。但我似乎不明白为什么我的代码总是返回4个多头而不是正确的多头数

牛和公牛的说明:公牛-无论位置如何,正确数字的数量。Cows-如果位置正确,则正确的位数

#Cows and Bulls game!
#User must correctly guess a computer-generated 4-Digit number.
#TASKS:
#1. Generate a random 4-digit number.
#2. Ask the user to enter the 4-Digit number.
#3. Compare the numbers obtained from the user and generated number.
#4. a correct digit at the correct place gives a cow.
#5. a correct digit at a wrong place gives a bull.
#6. the game continues until the user correctly guesses the number.

import random

cowsNbulls = {
    'cow': 0,
    'bull': 0,
  }

cpu_num = random.sample(range(0,9),4)
print(cpu_num)
num_tries = 0

correct_num = False
while not correct_num:
    user_input = int(input("Please choose a 4 digit number: \n"))
    user_num = [int(i) for i in str(user_input)]
    cowsNbulls['cow'] = 0
    cowsNbulls['bull'] = 0
    if user_num == cpu_num:
        correct_num = True
        print("Yay you got the number in {} tries!".format(num_tries))
    if user_num != cpu_num:
        for i in range(len(user_num)):
            if user_num[i] == cpu_num[i]:
                cowsNbulls['cow'] += 1
            if user_num[i] in cpu_num:
                cowsNbulls['bull'] += 1
        print(str(cowsNbulls['cow']), "Cows.", str(cowsNbulls['bull']), "Bulls")
    num_tries +=1

这是它生成的代码:(我还打印了数字,以手动检查计算机生成的数字。)

[0, 2, 4, 8]
Please choose a 4 digit number: 
8402
0 Cows. 4 Bulls
Please choose a 4 digit number: 
0000
1 Cows. 4 Bulls
Please choose a 4 digit number: 
9999
0 Cows. 0 Bulls
Please choose a 4 digit number: 
2222
1 Cows. 4 Bulls
Please choose a 4 digit number: 

Tags: thenumbercpunumpleasedigitchooseuser
1条回答
网友
1楼 · 发布于 2024-10-04 11:27:17

在循环的每次迭代中,您都在测试cow和bull(即使它已经找到了cow)

你会想要改变的

            if user_num[i] == cpu_num[i]:
                cowsNbulls['cow'] += 1
            if user_num[i] in cpu_num:
                cowsNbulls['bull'] += 1

致:

            if user_num[i] == cpu_num[i]:
                cowsNbulls['cow'] += 1
            elif user_num[i] in cpu_num:
                cowsNbulls['bull'] += 1

只有在没有发现母牛的情况下,才会对公牛进行测试

您可以通过添加一个额外的bull检查来完成类似的操作,如下所示: if user_num[i] in cpu_num and user_num[i] != cpu_num[i]:

但在我看来,第一种选择更干净

相关问题 更多 >