Better way for concatenating two sorted list of integers

anand

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(mxn) in worst case, how can I make it perform better ?

Padraic Cunningham

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]

編集
0

コメントを追加

0

関連記事

分類Dev

Is there a way to measure how sorted a list is?

分類Dev

Is there a better way to run this function on two separate elements?

分類Dev

merge two sorted list of items in python

分類Dev

Better way to check a list for specific elements - python

分類Dev

A better way to slice an array (or a list) in powershell

分類Dev

Most efficient way to get sorted indices based on two numpy arrays

分類Dev

Is there a way to compare the corresponding integers in two numbers without converting them to arrays

分類Dev

Is there a better way to check these two variables instead of four ifs?

分類Dev

Generate an array of integers from text file of strings on separate lines. Better way?

分類Dev

fastest way to find insert position for new data into sorted list of dates

分類Dev

Question about merge two sorted list(leetcode question 21)

分類Dev

Quickest way to count number of repeated leading integers in a list

分類Dev

Python way of getting max of list containing integers and floats

分類Dev

Better way to create edge list matrix using an adjacency matrix

分類Dev

better way to get a list of variable length strings in fortran

分類Dev

Better way to write this "double-barreled list" in Python

分類Dev

Finding missing integers in a sorted array

分類Dev

Concatenating a list of files using For loop

分類Dev

Searching a swap-sorted array of distinct integers

分類Dev

Problem with Printing Integers from Sorted Set in Scala

分類Dev

Is there a better way of comparing dates

分類Dev

A better way to detect the cursor?

分類Dev

Better way to return boolean

分類Dev

A better way to introspect a capture

分類Dev

Is there a better way to do this? BASH

分類Dev

better way to do this in MATLAB?

分類Dev

Is there a better way to loop code?

分類Dev

Concatenating two columns together in R with NAs

分類Dev

using sql concat() in django for concatenating two columns

Related 関連記事

  1. 1

    Is there a way to measure how sorted a list is?

  2. 2

    Is there a better way to run this function on two separate elements?

  3. 3

    merge two sorted list of items in python

  4. 4

    Better way to check a list for specific elements - python

  5. 5

    A better way to slice an array (or a list) in powershell

  6. 6

    Most efficient way to get sorted indices based on two numpy arrays

  7. 7

    Is there a way to compare the corresponding integers in two numbers without converting them to arrays

  8. 8

    Is there a better way to check these two variables instead of four ifs?

  9. 9

    Generate an array of integers from text file of strings on separate lines. Better way?

  10. 10

    fastest way to find insert position for new data into sorted list of dates

  11. 11

    Question about merge two sorted list(leetcode question 21)

  12. 12

    Quickest way to count number of repeated leading integers in a list

  13. 13

    Python way of getting max of list containing integers and floats

  14. 14

    Better way to create edge list matrix using an adjacency matrix

  15. 15

    better way to get a list of variable length strings in fortran

  16. 16

    Better way to write this "double-barreled list" in Python

  17. 17

    Finding missing integers in a sorted array

  18. 18

    Concatenating a list of files using For loop

  19. 19

    Searching a swap-sorted array of distinct integers

  20. 20

    Problem with Printing Integers from Sorted Set in Scala

  21. 21

    Is there a better way of comparing dates

  22. 22

    A better way to detect the cursor?

  23. 23

    Better way to return boolean

  24. 24

    A better way to introspect a capture

  25. 25

    Is there a better way to do this? BASH

  26. 26

    better way to do this in MATLAB?

  27. 27

    Is there a better way to loop code?

  28. 28

    Concatenating two columns together in R with NAs

  29. 29

    using sql concat() in django for concatenating two columns

ホットタグ

アーカイブ