如何修复这段代码,用于冒泡排序。

huangapple go评论59阅读模式
英文:

How can I fix this code, for shaker sorting

问题

def cocktail_sort(seq: list):
    for i in range(len(seq) - 1, 0, -1):
        swapped = False
        for j in range(i, 0, -1):
            if seq[j] < seq[j - 1]:
                temp = seq[j]
                seq[j] = seq[j - 1]
                seq[j - 1] = temp
                swapped = True
        for j in range(i):
            if seq[j] > seq[j + 1]:
                temp2 = seq[j]
                seq[j] = seq[j + 1]
                seq[j + 1] = temp2
                swapped = True
        if not swapped:
            return seq

lst = [15, 4, 7, 2, 1, 20]
print(cocktail_sort(lst))

TypeError: object of type 'type' has no len()
英文:
def cocktail_sort(seq: list):
    for i in range (len(list) -1, 0, -1):
        swapped = False
        for j in range(i, 0, -1):
            if list[j] &lt; list[j-1]:
                temp = list[j]
                list[j] = list[j-1]
                list[j-1] = temp
                swapped = True
        for j in range(i):
            if list[j] &gt; list[j+1]:
                temp2 = list[j]
                list[j] = list[j+1]
                list[j+1] = temp2
                swapped = True
            if not swapped:
                return list
lst = [15, 4, 7, 2, 1, 20]               
print(cocktail_sort(lst))

TypeError: object of type 'type' has no len()

I tried to find a solution to the problem on YouTube and forums, I sat several times and thought about what to do. I'm just a beginner and I don't really understand.

答案1

得分: 1

在你的函数头部,你把参数写成了 seq: list。这表示“我想要一个名为 seq 的输入参数,它必须是类型为 list”。

然而,在你的函数内部,你试图使用 list 来引用你的输入参数。你应该使用 seq 来引用你的输入参数。

错误基本上是在说“list 是一种类型,不是一个变量”,无论你在哪里尝试使用 list


在函数头部不一定需要指定类型,但如果你想使用类型提示,我建议查看这里的文档:https://docs.python.org/3/library/typing.html

英文:

In your function header you have your argument written as seq: list. This means "I would like one input parameter called seq and it must be of type list".

However, inside your function, you are trying to use list to reference your input parameter. You should instead be using seq to reference your input parameter.

The error is basically saying "list is a type, not a variable" wherever you've tried to use list.


You don't necessarily need to specify a type in your function header, but if you would like to use the type hinting, I would recommend having a look at the documentation here: https://docs.python.org/3/library/typing.html

答案2

得分: 0

你在顶部意外地写成了 len(list) 而不是 len(seq)

英文:

You have accidentally (at the top) put len(list) instead of len(seq)

huangapple
  • 本文由 发表于 2023年1月8日 22:19:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048459.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定