类型错误:不支持-:“str”和“int”(Python)的操作数类型

2024-06-01 02:44:27 发布

您现在位置: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'


Tags: thekey代码indexifdef错误low
3条回答

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

您在代码中将“n”声明为字符串。尝试用字符串执行算术运算。

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

它会起作用的!!!

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

n = int(n)

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

arr = eval(arr)

相关问题 更多 >