提问人:is200 提问时间:11/17/2023 最后编辑:quamranais200 更新时间:11/17/2023 访问量:58
请Helllpppp。搜索算法不起作用,不知道为什么 [关闭]
Helllpppp please.Search algorithm not working no idea why [closed]
问:
oldlist=[4,7,2,11,9]
newlist=[]
print(oldlist)
minimum=oldlist[0]
length=len(oldlist)
while length != 0:
for i in range(1,length):
if minimum > oldlist[i]:
minimum=oldlist[i]
else:
continue
oldlist.remove(minimum)
length=len(oldlist)
newlist.append(minimum)
print(oldlist,newlist)
以上是我的代码
myList=[34,12,6,78,100,25]
newList=[]
print(myList)
length=len(myList)
while length!=0:
lowest=myList[0]
for i in range(1,length):
if myList[i]<lowest:
lowest=myList[i]
else:
continue
myList.remove(lowest)
length=len(myList)
newList.append(lowest)
print(myList," ",newList)
这是我的老师守则。
老师的代码排序算法效果很好,我的则不然。我知道有一些差异,但它们几乎完全相同,请解释为什么我的不起作用。
我预计列表会从低到高。尝试更改 while to 以移动列表调整,但丝毫不知道还能做什么。
答:
0赞
lem
11/17/2023
#1
几乎正确!你忘了放在 while 循环中minimum=oldlist[0]
oldlist=[4,7,2,11,9]
newlist=[]
print(oldlist)
length=len(oldlist)
while length != 0:
minimum=oldlist[0]
for i in range(1,length):
if minimum > oldlist[i]:
minimum=oldlist[i]
else:
continue
oldlist.remove(minimum)
length=len(oldlist)
newlist.append(minimum)
print(oldlist,newlist)
-1赞
NoStepOnSnek
11/17/2023
#2
# Sorting algorithm
oldlist=[4,7,2,11,9]
newlist=[]
length=len(oldlist)
while length != 0:
minimum = oldlist[0]
for i in range(0,length):
print(i,"i")
if minimum > oldlist[i]:
minimum=oldlist[i]
oldlist.remove(minimum)
length=len(oldlist)
newlist.append(minimum)
print(newlist)
- 每次 while 循环迭代时,都必须重置最小值。
- else -> continue 语句是不必要的。在这种情况下,您不需要跳过迭代。
评论
0赞
Barmar
11/17/2023
从何而来?如果所有元素都超过 999 怎么办?999
评论
else: continue