def countSwaps(a):
count = 0
for i in range(len(a)-1):
for j in range(len(a)-1-i):
count += 1
if a[j] > a[j+1]:
a[j],a[j+1] = a[j+1],a[j]
return count
countSwaps()
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().rstrip().split()))
countSwaps(a)
抛出运行时错误
有人能帮我吗?我在这里错过了什么?
非常感谢!
def countSwaps(a):
count = 0
for i in range(len(a)-1):
for j in range(len(a)-1-i):
count += 1
if a[j] > a[j+1]:
a[j],a[j+1] = a[j+1],a[j]
return count
countSwaps()
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().rstrip().split()))
countSwaps(a)
返回错误
TypeError: countSwaps() missing 1 required positional argument: 'a'
所以我删除了countSwaps()
,之后我输入:
1
2 3 4 5
为了避免n
的创建失败,我首先输入了一个数字。然后是一个用空格分隔的数字列表。这样做不会引发错误。
首先,在第10行中的列表初始化之前,您在主块外调用了函数,即countSwaps()
。如果您希望它同时工作,则必须在定义中为它提供一个关键字参数,即def countSwaps(a=[1, 3, 4, 2]):
。在这个代码中,甚至没有使用n
,这降低了代码的质量。
简而言之:删除第10行countSwaps()
或在定义中添加关键字参数。