Lets assume I have one list and another tuple both of them are already sorted:
A = [10, 20, 30, 40]
B = (20, 60, 81, 90)
What I would need is to add all the elements from B into A in such a way that A remains sorted.
Solution I could come with was:
for item in B:
for i in range(0, len(A)):
if item > A[i]:
i += 1
else:
A.insert(i, item)
assuming A of size m, and B of size n; this solution would take O(mx
n) in worst case, how can I make it perform better ?
A simple way would be heapq.merge:
A = [10, 20, 30, 40]
B = (20, 60, 81, 90)
from heapq import merge
for ele in merge(A,B):
print(ele)
Output:
10
20
20
30
40
60
81
90
Some timings using the other O(n)
solution:
In [53]: A = list(range(10000))
In [54]: B = list(range(1,20000,10))
In [55]: timeit list(merge(A,B))
100 loops, best of 3: 2.52 ms per loop
In [56]: %%timeit
C = []
i = j = 0
while i < len(A) and j < len(B):
if A[i] < B[j]:
C.append(A[i])
i += 1
else:
C.append(B[j])
j += 1
C += A[i:] + B[j:]
....:
100 loops, best of 3: 4.29 ms per loop
In [58]: m =list(merge(A,B))
In [59]: m == C
Out[59]: True
If you wanted to roll your own this is a bit faster than merge:
def merger_try(a, b):
if not a or not b:
yield chain(a, b)
iter_a, iter_b = iter(a), iter(b)
prev_a, prev_b = next(iter_a), next(iter_b)
while True:
if prev_a >= prev_b:
yield prev_b
try:
prev_b = next(iter_b)
except StopIteration:
yield prev_a
break
else:
yield prev_a
try:
prev_a = next(iter_a)
except StopIteration:
yield prev_b
break
for ele in chain(iter_b, iter_a):
yield ele
Some timings:
In [128]: timeit list(merge(A,B))
1 loops, best of 3: 771 ms per loop
In [129]: timeit list(merger_try(A,B))
1 loops, best of 3: 581 ms per loop
In [130]: list(merger_try(A,B)) == list(merge(A,B))
Out[130]: True
In [131]: %%timeit
C = []
i = j = 0
while i < len(A) and j < len(B):
if A[i] < B[j]:
C.append(A[i])
i += 1
else:
C.append(B[j])
j += 1
C += A[i:] + B[j:]
.....:
1 loops, best of 3: 919 ms per loop
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加