[英]Inversion Counting Algorithm implementation in Python,cannot unpack non-iterable int object
This is my implementation of the inversion counting algorithm using a divide and conquer approach, the problem i am having is it keeps saying there is a type error, cannot unpack non-iterable int object, in line 45, and line 10这是我使用分而治之的方法实现反转计数算法,我遇到的问题是它一直说存在类型错误,无法解压缩不可迭代的 int object,在第 45 行和第 10 行
# count the number of inversions
def SortandCount(A:list):
length = len(A)
mid = length//2
firsthalf = A[ : mid]
secondhalf = A[mid :]
if length == 1:
return 0
else:
B, X = SortandCount(firsthalf)
C, Y = SortandCount(secondhalf)
D, Z = CountSplitInv(B, C)
return D, X + Y + Z
def CountSplitInv(B,C):
# takes 2 sorted list B C merging it into sorted list D
# as well as counting the inversions
# B = [1,4] C[2,3,5]
invnum = 0
D = []
i = j = 0
length = len(B)
while i < length and j <len(C):
if (B[i] <= C[j] ):
D.append(i)
i +=1
if(B[i] > C[j]):
D.append(C[j])
j+=1
invnum += len(B) - i
if(i != length):
D.extend(B[i:])
if(j != len(C)):
D.extend(C[j:])
return D,invnum
def inversions_countin_wrapper(lst: list) -> int:
return SortandCount(lst)[1]
A=[14,2,3]
num=SortandCount(A)
print(num)
the error is错误是
Traceback (most recent call last):
File "/Users/Algorithms/divide&conquer/inversion.py", line 45, in <module>
num=SortandCount(A)
File "/Users/Algorithms/divide&conquer/inversion.py", line 10, in SortandCount
B, X = SortandCount(firsthalf)
TypeError: cannot unpack non-iterable int object
Appreciate any kind of help,!!感谢任何形式的帮助,!! Please !!!请 !!! Been stuck on this for 3 days (stupid ,i know) >_8<被困在这个问题上 3 天(愚蠢,我知道)>_8<
B, X = SortandCount(firsthalf)
Requires SortandCount
to return two values.要求SortandCount
返回两个值。 If the function executes to the end, it will do so.如果 function 执行到最后,它就会这样做。 But what if it terminates early?:但是如果它提前终止呢?
if length == 1:
return 0
Then it only returns a 0. So there's no value for X
.然后它只返回一个 0。所以X
没有价值。 Which is what the error message is telling you.这就是错误消息告诉您的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.