TypeError: unsupported operand type(s) for -: 'str' and 'int' (Python)

TypeError: unsupported operand type(s) for -: 'str' and 'int' (Python)

我已经在 python 中编写了快速排序的代码,但是这段代码抛出了错误。

----------


    k=0
    def partition(arr,low_index,high_index):
        key = arr[low_index]
        i = low_index + 1;
        j = high_index

        while True:
            while (i<high_index and key>=arr[i]):
                i+=1
            while (key<arr[j]):
                j-=1
            if i<j:
                arr[i,j] = arr[j,i]
            else:
                arr[low_index,j]=arr[j,low_index]
                return j

    def quicksort(arr,low_index,high_index):
         if low_index < high_index:
            j = partition(low_index,high_index,arr)
            print("Pivot element with index "+str(j)+" has thread "+str(k))
            if left<j:
                k=k+1
                quicksort(arr,low_index, j - 1)
            if i<right:
                k=k+1
                quicksort(arr,j+1,high_index)
         return arr

    n = input("Enter the value n ")
    arr=input("Enter the "+str(n)+" no. of elements ")
    brr=quicksort(arr,0,n-1)
    print("Elements after sorting are "+str(brr))

----------

它抛出的错误是

Enter the value n 4

Enter the 4 no. of elements [5,6,2,7] Traceback (most recent call last): File "C:\Users\devendrabhat\Documents\dev\dev\quick.py", line 38, in brr=quicksort(arr,0,n-1) TypeError: unsupported operand type(s) for -: 'str' and 'int'

您需要将 n 更改为整数,而不是字符串。您的错误告诉您,您正在尝试对字符串和整数执行操作(在本例中)。将 str(n) 更改为 int(n) 以便您始终具有相同的类型。

n 是字符串。所以你需要把它改成int:

n = int(n)

如果您在第 37 行输入 [5,6,2,7],python 会将其解释为类似“[5,6,2,7]”的字符串。 因此,您需要将字符串转换为列表。

arr = eval(arr)

您在代码中将 'n' 声明为字符串。并尝试对字符串进行算术运算。

所以它给出了那个错误。将此 str(n) 更改为 int(n)

它会起作用的!!!