我是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
答案 0 :(得分:1)
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上提问。你可以在互联网上找到许多类似的答案
答案 1 :(得分:1)
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))
答案 2 :(得分:0)
如果您对代码失败的原因感兴趣而不是复制粘贴答案:
我不知道if minimum
应该完成什么,但它的作用是每次minimum != 0
执行循环,因为它会评估为True
并且因为or
{1}}已短路,int(positions) < minimum
未被检查,因此只需删除if minimum
。
您应该将最小值初始化为列表的第一个元素,因为您无法确定其中是否包含0。