1

确定有多少个数相等。打印该数字(零、二或三)以及一些描述性文本,以告知用户正在打印到屏幕上的内容

这只有时有效,我知道必须有一种更有效的方法,但是自从我刚开始学习 python 以来,我很难想到其他的东西。

#Taking the inputs from the user 
x,y,z = input("Enter the three valaues: ").split()

while True:
    if x!= y and x!=z:
      print("there is no equal numbers")
      break
    elif x==y or x==z:
      print("There are two equals numbers")
      break 
    else 
      print("There are three equals numbers")
4

3 回答 3

2

你错过了y == zbut的情况x != y

一个更具可读性的实现是:

if x == y == z:
    print("Three equal numbers")
elif x != y and y != z and x != z:
    print("No equal numbers")
else:
    print("Two equal numbers")

此外,您while应该出现在您的input行之前,以便它询问用户一组新的数字。


于 2021-02-24T01:51:46.603 回答
2

使用集合求相等数的计数:

lst = input("Enter 3 values, delimited by blanks: ").split()
num_equal = len(lst) - len(set(lst))
if num_equal:
    num_equal += 1
print(f'There are {num_equal} equal numbers')
于 2021-02-24T01:57:15.520 回答
0

由于您要处理 3 个值,因此与其他两个答案略有不同的方法是使用 aset和 a dict

num_equal = 3 - len({x, y, z})
print({0: "No equal numbers", 1: "Two equal numbers", 2: "All three equal"}[num_equal])
于 2021-02-24T02:37:13.420 回答