【问题标题】:Python guessing 2 numbers gamePython猜2个数字游戏
【发布时间】:2020-10-27 21:28:50
【问题描述】:

问题是

编写一个程序,将两个随机生成的介于 1 和 100 之间的自然数(正整数)的和 (a+b) 和乘积 (a*b) 打印给用户。要赢得游戏,用户必须猜出这两个数字,猜测的顺序应该无关紧要。给用户三个猜测,如果在三个猜测之后他们是错误的,那么数字就会显示给他们。用户必须在单轮中正确猜测两个猜测,并且不会被告知前一轮中的一个数字是否正确。 用户有 3 次尝试猜这两个数字,如果用户猜对了数字,则游戏应该结束。

import random
a = random.randint(1,100)
b = random.randint(1,100)

print("Sum of two random number is",a + b)
print("Product of two random number is", a * b)
print("Try to guess the 2 numbers that make this sum and product, you have 3 tries, good luck!")

count = 0
win = 0

while count != 3:
    guess_a = int(input('Guess first number '))
    guess_b = int(input('Guess second number '))
    
    if count == 3:
        break
        
    if ((guess_a == a) or (guess_b == b)) and ((guess_b == a) or (guess_a == b)):
        win = 1
        break
        
    else:
        count = count + 1
        print('Incorrect!!!')

if win == 1:
    print('Congrats you won the game.')
    
else:
    print('You lost the game.')
    print('Number a was:',a)
    print('Number b was',b)

我试过这个它有点工作,但我不知道如何使猜测数字的顺序无关紧要。

【问题讨论】:

  • 试试:((guess_a == a) and (guess_b == b)) or ((guess_b == a) and (guess_a == b))
  • 使用set:{guess_a, guess_b} == {a, b}
  • @hiroprotagonist 如果 a 和 b 恰好相同怎么办?
  • 设置的解决方案非常整洁。如果 a 和 b 相同,它仍然可以工作,请尝试一下,然后您需要输入相同的数字才能正确。顺便说一句,任何具有基本数学技能的人都不需要“猜测”答案;-)
  • @rajah9 {3, 3} == {3, 3}True。或者你认为什么行不通?

标签: python


【解决方案1】:

一种方法是根本不使用布尔值。

由于0在条件语句中会自动转换为False,所以如果某个条件为真,我们可以只写一个等于0的表达式。

我想出的表达方式是:

is_guess_a_right = (a - guess_a) * (a - guess_b)
is_guess_b_right = (b - guess_a) * (b - guess_b)
are_both_right = is_guess_a_right + is_guess_b_right

如果最终表达式等于 0,那么两个表达式都是正确的,换句话说,guess_a 和guess_b 等于 a 和 b(因为如果它们相同,a - guess_a 将等于零)。

最终代码:

import random

a = random.randint(1, 100)
b = random.randint(1, 100)

print("Sum of a and b is %s" % (a + b))
print("Product of a and b is %s" % (a * b))
print("You have three tries to guess the numbers")

count = 0

while count < 3:
    guess_a = int(input("Guess the first number: "))
    guess_b = int(input("Guess the second number: "))

    lose = (guess_a - a) * (guess_a - b) + (guess_b - a) * (guess_b - b)

    if lose:
        print("Try again")
        count += 1
    else:
        print("Congrats, you won the game")
        print("The two numbers were %s and %s" % (a, b))
        break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-21
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2021-02-01
    • 2021-05-18
    相关资源
    最近更新 更多