天哪,请。搜索算法不起作用,不知道为什么

问题描述 投票:0回答:2
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 来移动列表调整,但没有丝毫线索还能做什么。

python sorting
2个回答
1
投票

几乎正确!您忘记将

minimum=oldlist[0]
放入 while 循环中

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)

0
投票
# 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 语句是不必要的。在这种情况下,您不需要跳过迭代。
© www.soinside.com 2019 - 2024. All rights reserved.