如何在python中不使用min函数,同时使用while循环从列表中查找最小值

2024-10-01 13:42:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python有点陌生,最近遇到了一个我无法理解的问题,即如何在不使用python中的min或max函数的情况下找到列表的最小值。以下是我的代码:

#Prompt user to enter a minimum of 5 round trip times separated with commas
roundTrips = input('Please enter at least 5 round trips seprated by ",": ')



#Check closest object
def closest_object(roundTrips):
    roundTrips = list(roundTrips.split(','))
    count = 0
    minimum = 0
    if len(roundTrips)<=4:
        print('error')
    else:
        while count<len(roundTrips):
            positions = roundTrips[count]
            count += 1
            if minimum or (int(positions)<minimum):
                minimum = positions
                print(minimum)

    #Perform the parsing of roundTrips input here

    closestObject = []

    print('The closest object is',closestObject) #Modify to display the closest object

    return closestObject#Do not remove this line

Tags: oftoinputlenifobjectcountprint
3条回答
lst = [10, 1,2,3,4,5]
ans = lst[0]
i=0
while(i<len(lst)):
    if lst[i] < ans:
        ans = lst[i]
    i+=1
print(ans)

这是可行的,但我不认为这样简单的任务,你需要问关于stackoverflow的问题。你可以在网上找到许多类似的答案

def find_min(l):
  min = l[0]
  for i in l[1:]:
    if i<min: min = i
  return(min)

la=[4,2,3,4,5,3,2,4,44,-2]

print(find_min(la))

如果您对代码失败的原因而不是复制粘贴感兴趣,请回答:

我不知道if minimum应该完成什么,但它所做的是每次minimum != 0执行循环,因为它的计算结果是True,并且由于{}短路,int(positions) < minimum没有被检查,所以只需删除{}。在

你应该将最小值初始化为列表的第一个元素,因为你不能确定0在其中。在

相关问题 更多 >