python - 类型错误 : unsupported operand type(s) for -: 'str' and 'int' (Python)

标签 python python-2.7 python-3.x ipython quicksort

我已经用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 是字符串。所以需要将其改为int:

n = int(n)

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

arr = eval(arr)

关于python - 类型错误 : unsupported operand type(s) for -: 'str' and 'int' (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42219874/

相关文章:

python - 如果我想使用无法通过 TensorFlow 加载到内存中的大型数据集,我该怎么办?

python - 线性回归中的交叉验证

python -/admin/ 'set' 对象的类型错误是不可逆的,并且要反转的参数 ( ) 必须是一个序列

python - QTreeWidget如何给子项添加复选框?

python-3.x - 如何安装 Selenium

python - 如何根据列名将数据框拆分为多个数据框

python,如何判断返回的是什么类型的obj

python - Python 2.7 的哪个微版本引入了集合理解?

python - 语法错误 : Non-ASCII character '\xe2'

javascript - Python/JavaScript/HTML 动态创建计算机网络图