英文:
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] < 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] > 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论