蟒蛇。找到最大数量和最小数量

时间:2016-10-19 22:29:11

标签: python

当我输入一个像[2,6,9,4,8​​,7]这样的数字序列来找到最大和最小的数字时,它表示(8,7)是最大和最小的数字是什么错误在我的代码?

def minmax():

    x = int(input("Enter the number of integers you want: "))

    mylist = [int(z) for z in input("Enter the numbers separated by a space and then click Enter: ").split()]


    l = mylist[0]

    for i in range(1, x):
        if mylist[i] > mylist[i - 1]:
            l = mylist[i]
        else:
            a = i
            while a < x - 1:
                if mylist[a + 1] > l:
                    l = mylist[a + 1]
                a += 1

    s = mylist[0]

    for i in range(1, x):
        if mylist[i] < mylist[i - 1]:
            s = mylist[i]
        else:
            a = i
            while a < x - 1:
                if mylist[a + 1] < s:
                    s = mylist[a + 1]
                a += 1

    print((l, s), "are the largest and smallest numbers")

minmax()

2 个答案:

答案 0 :(得分:2)

如何简单地使用min()max()功能?例如:

>>> my_list =  [2, 6, 9, 4, 8 ,7]
>>> min(my_list)
2
>>> max(my_list)
9

考虑到代码中的错误。您必须在if条件下进行更改。变化:

  • if mylist[i] > mylist[i - 1] - &gt; if mylist[i] > l:

  • if mylist[i] < mylist[i - 1] - &gt; if mylist[i] < s:

并删除else部分。

答案 1 :(得分:1)

如果你只想找到最大和最小的数字,你可以发出 else 语句。这有效:

x = int(input("Enter the number of integers you want: "))

mylist = [int(z) for z in input("Enter the numbers separated by a space and then click Enter: ").split()]


l = mylist[0]

for i in range(1, x):
    if mylist[i] > l:  # I changed mylist[i-1] to l
        l = mylist[i]


s = mylist[0]

for i in range(1, x):
    if mylist[i] < s:  # I changed mylist[i-1] to s
        s = mylist[i]


print((l, s), "are the largest and smallest numbers")

minmax()