您好我是python的新手,我在使用mergesort计数反转问题时遇到了麻烦。错误说“”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
答案 0 :(得分:1)
好吧,我不熟悉合并排序算法,但在get_number_of_inversions()
中你有两个出口:
首先:
number_of_inversions = 0
if right - left <= 1:
return number_of_inversions
和
return tot_inversions, sorted_list
您可以在表达式中使用返回值,如:
number_of_inversions_A, a[left:ave] = get_number_of_inversions(a, b, left, ave)
所以有时你会返回一个整数,有时候会返回一个元组。我的猜测是,当你返回一个整数时,就会出现这个错误。