gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:42:13 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com