[英]How to efficiently keep track of largest user inputted value?
I need to find the largest number the user input but I can not define the largest as a number, like I defined "largest = -9999999", any suggestions? 我需要找到用户输入的最大数字,但我不能将最大数字定义为数字,就像我定义的“最大= -9999999”,有什么建议吗? the "clargest" is to count how many time the largest number occurs
“澄清”是计算最大数量出现的时间
largest = -9999999
clargest = 0
while num != 0 :
num = input("Enter your number or type 0 to end: ")
if (num[0] == "-" and num[1:].isdigit()) or num.isdigit():
num = int(num)
if num != 0:
if num > largest:
clargest = 1
elif num == largest:
clargest = clargest + 1
largest = max(largest,num)
You can start with the mathematically meaningful largest = float('-inf')
, since the user is only allowed to enter (signed) integer numbers. 您可以从数学上有意义的
largest = float('-inf')
,因为只允许用户输入(带符号)整数。
Side note: there is a much simpler way of writing your loop: 旁注:编写循环有一种更简单的方法:
while num != 0 :
num = input("Enter your number or type 0 to end: ")
if (num[0] == "-" and num[1:].isdigit()) or num.isdigit():
num = int(num)
if num != 0:
# ... keep track of largest
would be simpler as: 会更简单:
while True:
try:
num = int(input("Enter..."))
except ValueError:
continue
if num == 0:
break
# ... keep track of largest
This use the recommended "it's better to ask forgiveness than permission" ( try
). 这使用了推荐的“请求宽恕而不是许可”(
try
)。 It also removes the repetition of num != 0
. 它还删除了
num != 0
的重复。 The test of "is this is number" is also more obvious. “这是数字”的测试也更加明显。 The need to have num be both a string and a number is also removed.
还要删除num为字符串和数字的需要。
You have a few options. 你有几个选择。 Here are two of them:
以下是其中两个:
Option 1: Keep a list of all the numbers that the user input, sort it, and take the last one. 选项1:保留用户输入的所有数字的列表,对其进行排序,然后选择最后一个。
Option 2: (I think this is what you're trying to do) Keep track of the largest number that has been entered so far. 选项2 :(我认为这是你要做的事情)跟踪到目前为止输入的最大数字。 Instead of defining largest as a large, negative number just keep around a boolean value that says if the input is the first number.
而不是将最大值定义为大的负数,而只是保持一个布尔值,该值表示输入是否是第一个数字。 The first number entered by the user is always the largest.
用户输入的第一个数字始终是最大的。 For you, specifically, when
clargest
is 0 you can set largest
to the user input. 对于您,具体来说,当
clargest
为0时,您可以将largest
设置为用户输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.