我已经用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
block 引用>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/