【发布时间】:2017-02-14 07:06:14
【问题描述】:
我已经在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))
----------
它抛出的错误是
输入值 n 4
输入 4 号。元素 [5,6,2,7] 回溯(最近一次通话最后): 文件“C:\Users\devendrabhat\Documents\dev\dev\quick.py”,第 38 行,在 brr=快速排序(arr,0,n-1) TypeError: 不支持的操作数类型 -: 'str' 和 'int'
【问题讨论】:
-
你能解释一下吗
-
Python 以字符串形式接收输入。您需要对该输入使用函数 int() 将其转换为整数并捕获可能的异常。
标签: python python-2.7 python-3.x ipython quicksort