我想将两个已排序的数组排序为一个。我正在使用合并排序。
错误:: IndexError:列表索引超出范围
我试过手动检查这个,但我找不到范围数组。如果我错了,请纠正我
def merging(list1, list2):
m = len(list1)
n = len(list2)
val = m+n
j, k = 0, 0
new =[]
for i in range(val):
if j<m and k<n:
if list1[j] < list2[k]:
new.append(list1[j])
j += 1
else:
new.append(list2[k])
k += 1
elif j==m:
while i<m+n:
new.append(list2[k])
k += 1
i += 1
else:
while i<m+n:
new.append(list1[j])
j += 1
i += 1
print 'sorted array is:', new
if __name__ == '__main__':
print 'Enter list 1'
l1 = raw_input()
list1 = map(int, l1.split())
print 'Enter list 2'
l2 = raw_input()
list2 = map(int, l2.split())
merging(list1,list2)
编辑::我不想使用任何内置函数,如sort()
答案 0 :(得分:1)
你有两个问题:
break
或elif
时,您没有else
,因此外部循环继续(并且for
循环忽略对{{1}的更改在循环内部制作);和i
。最小修正是:
return new
但你可以更整洁地应用相同的逻辑:
def merging(list1, list2):
m = len(list1)
n = len(list2)
val = m+n
j, k = 0, 0
new =[]
for i in range(val):
if j<m and k<n:
if list1[j] < list2[k]:
new.append(list1[j])
j += 1
else:
new.append(list2[k])
k += 1
elif j==m:
while i<m+n:
new.append(list2[k])
k += 1
i += 1
break # stop for loop here
else:
while i<m+n:
new.append(list1[j])
j += 1
i += 1
break # or here
return new # and return the output
答案 1 :(得分:0)
很抱歉混淆。
问题在于你不能改变i的值,因为i在范围(val)中。
def merging(list1, list2):
m = len(list1)
n = len(list2)
val = m+n
j, k = 0, 0
new =[]
for i in range(val):
if j<m and k<n:
if list1[j] < list2[k]:
new.append(list1[j])
j += 1
else:
new.append(list2[k])
k += 1
elif j==m:
if k<n:
new.append(list2[k])
k += 1
else:
if j<m:
new.append(list1[j])
j += 1
print "sorted array is:"
print new
if __name__ == '__main__':
print 'Enter list 1'
l1 = raw_input()
list1 = map(int, l1.split())
print 'Enter list 2'
l2 = raw_input()
list2 = map(int, l2.split())
merging(list1,list2)
答案 2 :(得分:0)
def merging(list1, list2):
m = len(list1)
n = len(list2)
res = []
a, b = 0, 0
while a < m and b < n:
if list1[a] < list2[b]:
res.append(list1[a])
a += 1
else:
res.append(list2[b])
b += 1
if a == m:
for i in list2[b:]:
res.append(i)
else:
for i in list1[a:]:
res.append(i)
return res
if __name__ == '__main__':
print 'Enter list 1'
l1 = raw_input()
list1 = map(int, l1.split())
print 'Enter list 2'
l2 = raw_input()
list2 = map(int, l2.split())
print merging(list1,list2)
答案 3 :(得分:0)
这是一个返回生成器并适用于所有迭代的版本:
def merge(g1, g2):
i1, i2 = iter(g1), iter(g2)
e1, e2 = None, None
try:
e1 = next(i1)
e2 = next(i2)
while True:
if e1 < e2:
yield e1
e1 = None
e1 = next(i1)
elif e2 < e1:
yield e2
e2 = None
e2 = next(i2)
else:
yield e1
yield e2
e1, e2 = None, None
e1 = next(i1)
e2 = next(i2)
except(StopIteration):
for ix, ex in ((i1, e1), (i2, e2)):
if ex != None:
yield ex
for e in ix:
yield e