TypeError:必须是str,而不是冒泡排序中的int

时间:2017-11-11 04:44:43

标签: python python-3.x bubble-sort

我在排序算法(冒泡排序)中的Python代码中出现了这种错误

  

回溯(最近一次调用最后一次):文件“D:\ CSC \ PYTHON SAMPLE CODES \ bubstepbystep.py”,第13行,       nlist = nlist + i TypeError:必须是str,而不是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 个答案:

答案 0 :(得分: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)