简体   繁体   中英

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

I have written the code for quick sort in python, but this code is throwing an error.

----------


    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))

----------

The error it is throwing is

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'

You need to change n to an integer, not a string. Your error is telling you, that you are trying to perform an operation (- in this case) on a string and an integer. Change str(n) to int(n) so you have the same type throughout.

you are declaring 'n' as string there in your code. And trying to perform arithmetic operation with string.

So it is giving that error. Change this str(n) to int(n) .

It will work !!!

n is string. So you need to change it to int:

n = int(n)

If you input [5,6,2,7] on line 37, python interpret it as string like "[5,6,2,7]". So, you need to convert string to list.

arr = eval(arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM