Merge Function Of Heapq Module In Python

Overview:

  • The merge() function takes multiple Python iterables as parameters.
  • For the merge() function to work correctly each of the input sequence should be in sorted order.

Example:

# Example Python program that merges multiple sorted sequences

# into one

import heapq

 

# Create sorted sequences

sequence1 = [1,2,3]; # A list

sequence2 = (5,7,9); # A tuple

sequence3 = {6,8,10}; # A set

 

# Merge the sequences

merged = heapq.merge(sequence1, sequence2, sequence3);

 

# Print the merged sequences

print("The merged sequence:");

for item in merged:

    print(item);

 

Output:

The merged sequence:

1

2

3

5

6

7

8

9

10

Example – With reverse comparisons:

import heapq

 

# Iterables

s1 = ('e', 'c', 'a');

s2 = ('f', 'd', 'b');

 

# Sort by specifying reversing each comparison while sorting

sorted = heapq.merge(s1, s2, reverse=True);

for element in sorted:

    print(element);

 

Output:

f

e

d

c

b

a

 

Example - Merge using a function that returns a comparison key:

# Example Python program that merges elements from two iterables

# using the merge function and a comparison key function

import heapq

 

# Circuit class definition

class Circuit:

 

    def __init__(self, name, distance):

        self.name = name

        self.distance = distance

 

# Create sorted lists of circuit instances       

c0 = Circuit("Circuit0", 10)

c1 = Circuit("Circuit1", 30)

c2 = Circuit("Circuit2", 40)

i1 = [c0, c1, c2]

 

c3 = Circuit("Circuit3", 15)

c4 = Circuit("Circuit4", 25)

c5 = Circuit("Circuit5", 35)

i2 = [c3, c4, c5]

 

# Key function used for comparison while sorting

def keyfunc(circuit):

    return circuit.distance

 

# Merge elements from two Python iterables whose elements are already in sorted order

merged = heapq.merge(i1, i2, key=keyfunc)

 

# Print the merged sequence

print("Merged sequence:")

for item in merged:

    print(item.distance)

 

 

Output:

Merged sequence:

10

15

25

30

35

40

 


Copyright 2022 © pythontic.com