Open In App

Python – Cross Join every Kth segment

Improve
Improve
Like Article
Like
Save
Share
Report

Given two lists, extract alternate elements at every Kth position.

Input : test_list1 = [4, 3, 8, 2, 6, 7], test_list2 = [5, 6, 7, 4, 3, 1], K = 3 
Output : [4, 3, 8, 5, 6, 7, 2, 6, 7, 4, 3, 1] 
Explanation : 4, 3, 8 after that 5, 6 from other list are extracted, and so on.

Input : test_list1 = [4, 3, 8, 2], test_list2 = [5, 6, 7, 4], K = 2 
Output : [4, 3, 5, 6, 8, 2, 7, 4] 
Explanation : 4, 3 after that 5, 6 from other list are extracted, and so on. 

Method #1: Using generator [yield] + loop

In this, we iterate for all elements, nested to get K elements at each pass from both list. The yield is used to dynamically return segments as they get processed.

Python3




# Python3 code to demonstrate working of
# Cross Join every Kth segment
# Using yield + loop
 
# helper function
def pair_merge(test_list1, test_list2, K):
    idx1 = 0
    idx2 = 0
    while(idx1 < len(test_list1)):
         
        # get K segments
        for i in range(K):
            yield test_list1[idx1]
            idx1 += 1
        for i in range(K):
            yield test_list2[idx2]
            idx2 += 1
 
# initializing lists
test_list1 = [4, 3, 8, 2, 6, 7]
test_list2 = [5, 6, 7, 4, 3, 1]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing K
K = 2
 
# calling helper func. in generator expression
res = [ele for ele in pair_merge(test_list1, test_list2, K)]
 
# printing result
print("The cross joined list : " + str(res))


Output

The original list 1 is : [4, 3, 8, 2, 6, 7]
The original list 2 is : [5, 6, 7, 4, 3, 1]
The cross joined list : [4, 3, 5, 6, 8, 2, 7, 4, 6, 7, 3, 1]

Time complexity: O(n*K), where n is length of list and K is given a number by user.
Auxiliary space: O(n), where n is length of res list.

Method #2 : Using zip_longest() + list comprehension

In this, we get all the elements for each list using zip_longest, and list comprehension is used for the task of iteration in both list.

Python3




# Python3 code to demonstrate working of
# Cross Join every Kth segment
# Using zip_longest() + list comprehension
from itertools import zip_longest, chain
 
# initializing lists
test_list1 = [4, 3, 8, 2, 6, 7]
test_list2 = [5, 6, 7, 4, 3, 1]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing K
K = 2
 
# zip_longest to get segments
res = [y for idx in zip(zip_longest(*[iter(test_list1)] * K),
      zip_longest(*[iter(test_list2)] * K)) for y in chain.from_iterable(idx) if y]
 
# printing result
print("The cross joined list : " + str(res))


Output

The original list 1 is : [4, 3, 8, 2, 6, 7]
The original list 2 is : [5, 6, 7, 4, 3, 1]
The cross joined list : [4, 3, 5, 6, 8, 2, 7, 4, 6, 7, 3, 1]

Time Complexity: O(n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”. 

Method #3 : Using reduce():

Algorithm:

  1. Import the required modules from itertools and functools.
  2. Initialize two lists test_list1 and test_list2.
  3. Print the original lists.
  4. Initialize a variable K as 2.
  5. Use the zip_longest() method to get the segments of length K from test_list1 and test_list2.
  6. Use chain.from_iterable() method to chain these segments and remove None values if present in the segments.
  7. Flatten the above-generated iterable into a list using list comprehension and assign it to res.
  8. Use reduce() method to concatenate the sublists of res into a single list.
  9. Print the cross-joined list.

Python3




from itertools import zip_longest, chain
from functools import reduce
 
# initializing lists
test_list1 = [4, 3, 8, 2, 6, 7]
test_list2 = [5, 6, 7, 4, 3, 1]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing K
K = 2
 
# using reduce() to get segments and cross join them
res = reduce(lambda x, y: x + list(y), zip_longest(*[iter(test_list1)] * K, *[iter(test_list2)] * K), [])
 
# printing result
print("The cross joined list : " + str(res))
#This code is contributed by Pushpa.


Output

The original list 1 is : [4, 3, 8, 2, 6, 7]
The original list 2 is : [5, 6, 7, 4, 3, 1]
The cross joined list : [4, 3, 5, 6, 8, 2, 7, 4, 6, 7, 3, 1]

Time Complexity: O(n), where n is the length of test_list1 and test_list2.
Auxiliary Space: O(n), where n is the length of test_list1 and test_list2.

METHOD 4:Using list concatenation and slicing

APPROACH:

This program takes two lists and a value of K as inputs, and cross joins every Kth segment of the two lists to produce a single list.

ALGORITHM:

1. Initialize an empty list to store the cross-joined list.
2. Use a for loop to iterate over every Kth segment of the two lists.
3. Slice the two lists using the current index i and i+K to get the Kth segments.
4. Concatenate the two segments using the + operator and append them to the cross-joined list.
5. Print the cross-joined list.

Python3




# input lists
list1 = [4, 3, 8, 2, 6, 7]
list2 = [5, 6, 7, 4, 3, 1]
K = 2
 
# cross join every Kth segment using list concatenation and slicing
cross_join_list = []
for i in range(0, len(list1), K):
    cross_join_list += list1[i:i+K] + list2[i:i+K]
 
# print the cross joined list
print("The cross joined list:", cross_join_list)


Output

The cross joined list: [4, 3, 5, 6, 8, 2, 7, 4, 6, 7, 3, 1]

Time Complexity: O(n), where n is the length of the input lists. The for loop iterates n/K times, and each iteration involves slicing two segments of length K and concatenating them using the + operator.

Space Complexity: O(n), where n is the length of the input lists. The cross-joined list could have a maximum length of 2n, if every element of both lists is included in the final list. However, in practice, the actual length of the cross-joined list would be much smaller than 2n, depending on the value of K and the contents of the lists.



Last Updated : 11 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads