Python 中的列表排序算法不 运行
List Sorting Algorithm in Python does not run
我正在制作一个名为“dumbstuff”的模块,只是出于业余爱好,似乎无法识别 problem.The 函数设置为接受列表和运算符以按升序对列表进行排序或降序。当我运行这个功能的时候,出现了一个黑屏,我已经弄了一段时间了,不知道是什么问题。
这是“dumbstuff”模块中的排序函数:
def sortlist(rawlist: list, operator: str, ifprint: bool):
looped = 0
done = 0
index = 0
sortedList = []
while (done == 0):
index = 0
looped = 0
#ascending sort
if (operator == "<"):
while (index < len(rawlist) - 1):
if (rawlist[index] > rawlist[index + 1]):
temp = rawlist[index]
rawlist[index] = rawlist[index + 1]
rawlist[index + 1] = temp
looped += 1
if (looped == 0): done = 1
sortedList = rawlist
#descending sort
if (operator == ">"):
while (index < len(rawlist) - 1):
if (rawlist[index] < rawlist[index + 1]):
temp = rawlist[index + 1]
rawlist[index + 1] = rawlist[index]
rawlist[index] = temp
looped += 1
if (looped == 0): done += 1
sortedList = rawlist
if (ifprint == True):
print(sortedList)
这是我尝试 运行 它通过的代码,它创建了一个包含 20 个随机整数的数组,
import random
import dumbstuff as ds
array = []
index = 0
while (index < 20):
array.append(random.randint(0, 20))
index += 1
ds.sortlist(array, "<", ifprint=True)
input()
但是,代码似乎从未 return 也从未向屏幕输出任何内容。
您需要在代码中的某处递增 index
。
也许您可以用 for 循环替换 while 循环。
#ascending sort
if (operator == "<"):
for index in range(len(rawlist) - 1): # Here.
while (index < len(rawlist) - 1):
通过此更改,它似乎可以工作 https://repl.it/repls/SilentDelectablePrinter。
我正在制作一个名为“dumbstuff”的模块,只是出于业余爱好,似乎无法识别 problem.The 函数设置为接受列表和运算符以按升序对列表进行排序或降序。当我运行这个功能的时候,出现了一个黑屏,我已经弄了一段时间了,不知道是什么问题。
这是“dumbstuff”模块中的排序函数:
def sortlist(rawlist: list, operator: str, ifprint: bool):
looped = 0
done = 0
index = 0
sortedList = []
while (done == 0):
index = 0
looped = 0
#ascending sort
if (operator == "<"):
while (index < len(rawlist) - 1):
if (rawlist[index] > rawlist[index + 1]):
temp = rawlist[index]
rawlist[index] = rawlist[index + 1]
rawlist[index + 1] = temp
looped += 1
if (looped == 0): done = 1
sortedList = rawlist
#descending sort
if (operator == ">"):
while (index < len(rawlist) - 1):
if (rawlist[index] < rawlist[index + 1]):
temp = rawlist[index + 1]
rawlist[index + 1] = rawlist[index]
rawlist[index] = temp
looped += 1
if (looped == 0): done += 1
sortedList = rawlist
if (ifprint == True):
print(sortedList)
这是我尝试 运行 它通过的代码,它创建了一个包含 20 个随机整数的数组,
import random
import dumbstuff as ds
array = []
index = 0
while (index < 20):
array.append(random.randint(0, 20))
index += 1
ds.sortlist(array, "<", ifprint=True)
input()
但是,代码似乎从未 return 也从未向屏幕输出任何内容。
您需要在代码中的某处递增 index
。
也许您可以用 for 循环替换 while 循环。
#ascending sort
if (operator == "<"):
for index in range(len(rawlist) - 1): # Here.
while (index < len(rawlist) - 1):
通过此更改,它似乎可以工作 https://repl.it/repls/SilentDelectablePrinter。