我模仿就地合并排序的答案https://stackoverflow.com/a/19086076/10892923
import unittest
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s")
#in-place merge sort
def merge_inplace(A, start, mid, end) -> "None":
left = A[start:mid]
right = A[mid:end]
i = 0
j = 0
for c in range(start,end): #c for cur
if (i < len(left) and left[i] <= right[j]) or i >= len(right):
A[c] = left[i]
i = i + 1
else:
A[c] = right[j]
j = j + 1
def mergeSort_inplace(A, lo, hi) -> "None":
if lo < hi - 1:
mid = (lo + hi) // 2
mergeSort_inplace(A,lo,mid)
mergeSort_inplace(A,mid,hi)
merge_inplace(A, lo, mid, hi)
class MyCase(unittest.TestCase):
def test_a(self):
A = [20, 30, 21, 15, 42, 45, 31, 0, 9]
mergeSort_inplace(A,0,len(A))
print(A)
unittest.main()
我仔细检查了逻辑并断言它很清楚,
否则报告错误。
ERROR: test_a (__main__.MyCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "mergeSort.py", line 31, in test_a
mergeSort_inplace(A,0,len(A))
File "mergeSort.py", line 24, in mergeSort_inplace
mergeSort_inplace(A,lo,mid)
File "mergeSort.py", line 24, in mergeSort_inplace
mergeSort_inplace(A,lo,mid)
File "mergeSort.py", line 26, in mergeSort_inplace
merge_inplace(A, lo, mid, hi)
File "mergeSort.py", line 15, in merge_inplace
A[c] = left[i]
IndexError: list index out of range
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
我无法找到错误,为什么它报告列表索引超出范围。
答案 0 :(得分:1)
您遇到了短路问题
更改
if (i < len(left) and left[i] <= right[j]) or j >= len(right):
到
if j >= len(right) or (i < len(left) and left[i] <= right[j]):
更多详细信息,请参阅python - Bug with logic operator "or"? - Stack Overflow
和Built-in Types — Python 3.7.3 documentation