[英]bubble sort in python:index out of range
I am new to python and I was trying out bubble sort.我是 python 的新手,我正在尝试冒泡排序。 Not able to find the error.无法找到错误。 Little help here.这里帮助不大。
def bubble(n, list):
for i in range(0, n):
for j in range(0, n - i - 1):
if list[j] > list[j + 1]:
list[j],list[j+1] = list[j + 1],list[j]
def main():
n = input('size')
n = int(n)
list = []
for i in range(0, n):
no = input('no')
list + [no]
bubble(n, list)
print(list)
main()
During execution, it's showing: line 4, in bubble if (list[j] > list[j + 1]): IndexError: list index out of range在执行期间,它显示:第 4 行,在气泡中 if (list[j] > list[j + 1]): IndexError: list index out of range
But I couldn't find out how.但我不知道怎么做。 The index always will be索引永远是
The first problem is that you don't convert the input('no')
to int
.第一个问题是您没有将input('no')
转换为int
。 It is not the cause of the current problem, but would cause problems later.它不是当前问题的原因,但会导致以后出现问题。
The second problem is that you use list
as a variable name.第二个问题是你使用list
作为变量名。 list
is a predefined Python class and you will overwrite it. list
是一个预定义的 Python 类,您将覆盖它。 Choose a different name.选择一个不同的名称。
The third problem is that you use list + [no]
.第三个问题是你使用list + [no]
。 That will not add no
to list
.这不会将no
添加到list
。 It would just store the output temporarily and delete it automatically.它只会临时存储输出并自动删除它。 There are 2 solutions: 1. Using +=
a += b
is equal to a = a + b
.有两种解决方案: 1. 使用+=
a += b
等于a = a + b
。 This is also the case for many arithmetical operators.许多算术运算符也是如此。 Just replace +
with +=
.只需将+
替换为+=
。 2. Using append
append
is faster. 2. 使用append
append
更快。 Use it like somelist.append(somevalue)
.像somelist.append(somevalue)
一样使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.