与Min& amp; Max python

时间:2017-10-16 02:39:49

标签: python

while True:
    reply = raw_input("Enter text, (type [stop] to quit): ")
    print reply.lower()
    if reply == 'stop':
        break
    x = min(reply)
    y = max(reply)
    print("Min is " + x)
    print("Max is " + y)

我试图创建一个包含while语句的语句,在该语句中它会询问一系列输入语句并将它们全部取出并找到所有输入数字的最小值和最大值。有人有任何解决方案?我一直试图解决这个问题一段时间没有运气。谢谢大家!

4 个答案:

答案 0 :(得分:0)

缩进在Python中很重要。对于minmax,您可以使用两个变量来跟踪这些数字并继续请求数字直到停止条件。

min = max = userInput = raw_input()
while userInput != "stop":
    if int(userInput) < int(min):
        min = int(userInput)
    elif int(userInput) > int(max):
        max = int(userInput)
    userInput = raw_input()
    print "Min is "+str(min)
    print "Max is "+str(max)

此处,第一个输入被视为minmax值。请注意,如果用户输入stop作为第一个值,minmax也将是stop。如果您澄清了更多用户输入约束,那就更好了。

答案 1 :(得分:0)

这是另一种方法。

while True:
    reply = raw_input("Enter numbers separated by commas. (type [stop] to quit): ")
    user_input = reply.split(',')
    if reply == 'stop':
        break
    x = map(float, user_input)
    y = map(float, user_input)
    values = (x, y)
    print("Min is " + str(min(x)))
    print("Max is " + str(max(y)))

输入:

5, 10, 5000

输出:

Enter numbers separated by commas. (type [stop] to quit): 5, 10, 5000
Min is 5.0
Max is 5000.0
Enter numbers separated by commas. (type [stop] to quit): 

答案 2 :(得分:0)

正如他们所提到的,您需要跟踪list以获取minmax。遵循您的代码结构:

l = []
while True:
    reply = raw_input("Enter text, (type [stop] to quit): ")
    print reply.lower()
    if reply == 'stop':
        break
    l.append(int(reply))        #store the values

x = min(l)
y = max(l)
print "Min is ", x 
print "Max is ", y

IMP:不要忘记int转化

您可以尝试的另一种space conservative方法是在获得输入时计算最小值和最大值。

import sys
#placeholders
maximum = -(sys.maxint) - 1     #highest negative value
minimum = sys.maxint     #highest positive value

while True:
    reply = raw_input("Enter text, (type [stop] to quit): ")
    print reply.lower()
    if reply == 'stop':
        break
    reply=int(reply)
    if reply<minimum :
        minimum = reply
    if reply>maximum :
        maximum = reply

print "Min is ", minimum
print "Max is ", maximum

答案 3 :(得分:0)

你的想法是正确的。你还没有使用min max作为变量名,这也很棒。如果你使用python 3,请在下面的代码中用 raw_input 替换输入关键字。

希望它有效! :)

minn=5000;
maxx=0;
while True:
    reply = input("Enter text, (type [stop] to quit): ")

    if int(reply) < int(minn):
        minn = int(reply)

    if int(reply) > int(maxx):
        maxx = int(reply)

    if reply == 'stop':
        break
    print("Min is " + str(minn))
    print("Max is " + str(maxx))