2017-11-11 45 views
0
我有这样那样的错误在我的Python代码排序算法(冒泡排序)

类型错误:必须str的,而不是在泡诠释排序

Traceback (most recent call last): File "D:\CSC\PYTHON SAMPLE CODES\bubstepbystep.py", line 13, in nlist = nlist + i TypeError: must be str, not int

我无法弄清楚发生了什么里面

。请帮帮我。

import time 

nlist = input("Enter series of numbers: ") 
swap = len(nlist) 
qty = len(nlist) 
print("Original:", nlist) 


for x in range(qty - 1): 
    for i in range(swap - 1): #swap 
    if nlist [i] > nlist [i+1]: 
     temp = nlist [i] 
     nlist = nlist + i 
     nlist [i+1] = temp 

     print("\nSwapping Index:", i,"and", i+1, "\n\rNew list:", nlist) 
     time.sleep(3) 
    else: 
     print("\nSwapping Index:", i,"and", i+1) 
     time.sleep(3) 
     print("Nothing to swap, skipping . . .") 
     time.sleep(3) 

swap -= 1 
+1

您在什么时候将从'input(...)'返回的字符串转换为数字列表? 你似乎试图在尝试交换值时增加整个列表'nlist'? python中的交换可以通过以下模式更简单地完成:'a,b = b,a' – Gavin

+1

您不希望'nlist [i] = nlist [i + 1]'在那里吗? –

+0

@JohnnyMopp它也给我一个错误 – Clark

回答

1

你的问题是你的输入,我想:它映射到正确的整数,事情看起来好多了。此外,您的交换代码不正确:

import time 

nlist = list(map(int, input("Enter series of numbers: ").split())) 
nlist 
swap = len(nlist) 
qty = len(nlist) 
print("Original:", nlist) 

for x in range(qty - 1): 
    for i in range(swap - 1): #swap 
     if nlist [i] > nlist [i+1]: 
      temp = nlist [i] 
      print(temp) 
      nlist [i] = nlist [i+1] 
      nlist [i+1] = temp 

      print("\nSwapping Index:", i,"and", i+1, "\n\rNew list:", nlist) 
      time.sleep(3) 
     else: 
      print("\nSwapping Index:", i,"and", i+1) 
      time.sleep(3) 
      print("Nothing to swap, skipping . . .") 
      time.sleep(3) 

swap -= 1 

print("Final:", nlist) 
+0

我在这里假设输入字符串像'5 6 7' – wp78de

+0

非常感谢你的解答。上帝保佑 – Clark

相关问题