Python find the minimum using for loops? [closed]

北城余情 提交于 2019-12-13 05:37:44

问题


I don't know how to make python "scan" through the list for a candidate and then go back to the loop again to find another candidate for the min.

    candidate = 0
    maximum = 0
    a = [12, 10, 50, 100, 24]
    for i in len(s):
        for j in range(len(s)):

回答1:


You can use the builtin min function to do this

a = [12, 10, 50, 100, 24]
print min(a)

If you really want to use loop,

minimum = a[0]
for number in a:
    if minimum > number:
       minimum = number
print minimum

You can use max function to find the maximum in a list.




回答2:


You can write your own function to handle this for any sort of iterable, including generators:

def my_minimum(iterable):
    iterable = iter(iterable)
    minimum = iterable.next()
    for i in iterable:
        if i < minimum:
            minimum = i
    return minimum

>>> a = [12, 10, 50, 100, 24]
>>> my_minimum(a)
10

Which takes generators:

>>> b = xrange(20)
>>> my_minimum(b)
0

However, as the others mentioned, Python has its own built-in min function, so I hope this question is purely academic.

>>> min(a)
10

Which also takes generators:

>>> b = xrange(20)
>>> min(b)
0



回答3:


Use the built-in min and max functions, like this:

>>> min([12,10,50,100,24])
10
>>> max([12,10,50,100,24])
100


来源:https://stackoverflow.com/questions/21359883/python-find-the-minimum-using-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!