嗨,我是 python 新手,我在使用合并排序的计数反转问题上遇到了麻烦。错误说“int”对象不可迭代。但是,我认为我在这个阶段没有迭代任何数字。由于我被困在这里,我不确定这段代码中是否还有更多错误..任何人都可以帮我弄清楚这是怎么回事?非常感谢。
import sys
def merge_and_count_inversions(x, y):
sorted_array = []
count = 0
i, j = 0, 0
#print ("inside merge", x, y)
while i < len(x) and j < len(y):
if x[i] > y[j]:
count += len(x) - i
sorted_array.append(y[j])
j += 1
else:
sorted_array.append(x[i])
i += 1
while i < len(x):
sorted_array.append(x[i])
i += 1
while j < len(y):
sorted_array.append(y[j])
j += 1
#print ("overall count = ", count )
#print ("sorted_array", sorted_array)
return count, sorted_array
def get_number_of_inversions(a, b, left, right):
number_of_inversions = 0
if right - left <= 1:
return number_of_inversions
ave = (left + right) // 2
number_of_inversions_A, a[left:ave] = get_number_of_inversions(a, b, left, ave)
#print ("left list", a[left : ave])
#print ("number_of_inversions left half = ", number_of_inversions )
number_of_inversions_B, a[ave:right] = get_number_of_inversions(a, b, ave, right)
#print ("right list", a[ave : right])
#print ("number_of_inversions left + right half = ", number_of_inversions )
number_of_inversions_C, sorted_list = merge_and_count_inversions(a[left:ave],a[ave:right])
tot_inversions = number_of_inversions_A + number_of_inversions_B + number_of_inversions_C
#print ("number_of_inversions overall = ", number_of_inversions )
return tot_inversions, sorted_list
input_ = input()
n, *a = list(map(int, input_.split())) #n is the length of a
b = n * [0]
get_number_of_inversions(a, b, 0, len(a))
print(get_number_of_inversions(a, b, 0, len(a)))
错误说:
<ipython-input-60-e1f94361f38a> in get_number_of_inversions(a, b, left, right)
33 ave = (left + right) // 2
34 print ("average = ", ave)
---> 35 number_of_inversions_A, a[left:ave] = get_number_of_inversions(a, b, left, ave)
36 print ("left list", a[left : ave])
37 print ("number_of_inversions left half = ", number_of_inversions )
<ipython-input-60-e1f94361f38a> in get_number_of_inversions(a, b, left, right)
33 ave = (left + right) // 2
34 print ("average = ", ave)
---> 35 number_of_inversions_A, a[left:ave] = get_number_of_inversions(a, b, left, ave)
36 print ("left list", a[left : ave])
37 print ("number_of_inversions left half = ", number_of_inversions )
TypeError: 'int' object is not iterable