【问题标题】:List Sorting Algorithm in Python does not runPython中的列表排序算法不运行
【发布时间】:2020-07-15 15:18:47
【问题描述】:

我正在制作一个名为“dumbstuff”的模块,只是作为一种爱好,似乎无法识别问题。该函数设置为接收一个列表和一个运算符,以升序或降序对列表进行排序。当我运行该函数时,出现一个空白屏幕,我已经使用了一段时间了,无法弄清楚是什么问题。

这是“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()

但是,代码似乎永远不会返回,也永远不会向屏幕输出任何内容。

【问题讨论】:

  • 必须尝试任何调试才能查看代码的进展情况?
  • 是的,谢谢指出,不敢相信我错过了这么小的东西

标签: python python-3.x python-module


【解决方案1】:

您需要在代码中的某处增加 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 2020-11-15
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    相关资源
    最近更新 更多