我试图使用冒泡排序对列表进行排序,并编写了此代码,但是出现了一个显示typeerror:'list'对象不可调用的错误。我在哪里弄错了?
我试图以不同的方式输入列表元素,例如,包括十进制数字等,但仍然无法正常工作。
def swap(a,b):
if a > b:
t = a
a = b
b = t
return a,b
def sort(list):
k=0
for i in range(len(list)):
for j in range(len(list)):
if list[j] > list[j+1]:
(a,b) = swap(list[j],list(j+1))
list[j] = a
list[j+1] = b
k+=1
print(k,' ',list)
else:
k+=1
continue
print(list)
list = [5,6,89,2,1,42,23,46,0,83]
sort(list)
我希望列表为[0,1,2,5,6,23,42,83,89]
答案 0 :(得分:2)
list(j+1)
是错误的。 “列表”对象不可调用。同样在冒泡排序中,第二个循环一直到列表ie. range(len(list)-1)
def swap(a,b):
if a > b:
t = a
a = b
b = t
return a,b
def sort(list):
k=0
for i in range(len(list)):
for j in range(len(list)-1): #Change Here
if list[j] > list[j+1]:
(a,b) = swap(list[j],list[j+1]) #Change here
list[j] = a
list[j+1] = b
k+=1
print(k,' ',list)
else:
k+=1
continue
print(list)
list = [5,6,89,2,1,42,23,46,0,83]
sort(list)
输出
3 [5, 6, 2, 89, 1, 42, 23, 46, 0, 83]
4 [5, 6, 2, 1, 89, 42, 23, 46, 0, 83]
5 [5, 6, 2, 1, 42, 89, 23, 46, 0, 83]
6 [5, 6, 2, 1, 42, 23, 89, 46, 0, 83]
7 [5, 6, 2, 1, 42, 23, 46, 89, 0, 83]
8 [5, 6, 2, 1, 42, 23, 46, 0, 89, 83]
9 [5, 6, 2, 1, 42, 23, 46, 0, 83, 89]
11 [5, 2, 6, 1, 42, 23, 46, 0, 83, 89]
12 [5, 2, 1, 6, 42, 23, 46, 0, 83, 89]
14 [5, 2, 1, 6, 23, 42, 46, 0, 83, 89]
16 [5, 2, 1, 6, 23, 42, 0, 46, 83, 89]
19 [2, 5, 1, 6, 23, 42, 0, 46, 83, 89]
20 [2, 1, 5, 6, 23, 42, 0, 46, 83, 89]
24 [2, 1, 5, 6, 23, 0, 42, 46, 83, 89]
28 [1, 2, 5, 6, 23, 0, 42, 46, 83, 89]
32 [1, 2, 5, 6, 0, 23, 42, 46, 83, 89]
40 [1, 2, 5, 0, 6, 23, 42, 46, 83, 89]
48 [1, 2, 0, 5, 6, 23, 42, 46, 83, 89]
56 [1, 0, 2, 5, 6, 23, 42, 46, 83, 89]
64 [0, 1, 2, 5, 6, 23, 42, 46, 83, 89]
[0, 1, 2, 5, 6, 23, 42, 46, 83, 89]
答案 1 :(得分:1)
swap(list[j],list(j+1))
应该是
swap(list[j],list[j+1])
至少那是语法错误的地方,没有检查算法
答案 2 :(得分:1)
当您使用'list' object not callable
而不是()
时发生错误[]
。要解决此问题,请将(a,b) = swap(list[j],list(j+1))
替换为(a,b) = swap(list[j],list[j+1])
以下代码给出了所需的结果。抱歉,由于缩进不良,感谢@delirium和@iBug:
功能:
def swap(a,b):
if a > b:
t = a
a = b
b = t
return a,b
def sort(list):
k=0
for i in range(len(list)):
for j in range(len(list)-1): #Change Here
if list[j] > list[j+1]:
(a,b) = swap(list[j],list[j+1]) #Change here
list[j] = a
list[j+1] = b
k+=1
#print(k,' ',list) #Change here
else:
k+=1
continue
print(list)
list = [5,6,89,2,1,42,23,46,0,83]
sort(list)