Python - Cross Pattern Pairs in List
Last Updated :
16 May, 2023
Given two lists, pair them diagonally, in cross pattern [works for even and equi-length lists].
Input : test_list1 = [4, 5, 6, 2], test_list2 = [9, 1, 4, 7]
Output : [(4, 1), (5, 9), (6, 7), (2, 4)]
Explanation : Crosslinked diagonally, 4->1, 5->9.
Input : test_list1 = [4, 5], test_list2 = [9, 1]
Output : [(4, 1), (5, 9)]
Explanation : Crosslinked diagonally, 4->1, 5->9.
Method #1: Using loop
In this, we iterate through list and test for even or odd index, in case of even index, we pair with next element of other list, or else we pair with previous element of other list. This way cross pattern tuples are formed.
Python3
# Python3 code to demonstrate working of
# Cross Pattern Pairs in List
# Using loop
# function to generate cross pattern pairs
def crossPair(test_list1, test_list2):
# lengths of both lists should be equal
if len(test_list1) != len(test_list2):
return -1
res = []
for idx in range(len(test_list1)):
# checking for conditions
if idx % 2 == 0:
res.append((test_list1[idx], test_list2[idx + 1]))
else:
res.append((test_list1[idx], test_list2[idx - 1]))
return res
# initializing lists
input_list1 = [4, 5, 6, 2, 8, 9]
input_list2 = [9, 1, 4, 7, 9, 2]
# printing original lists
print("The original list 1 is : " + str(input_list1))
print("The original list 2 is : " + str(input_list2))
# printing result
print("Paired List elements : ", crossPair(input_list1, input_list2))
Output:
The original list 1 is : [4, 5, 6, 2, 8, 9] The original list 2 is : [9, 1, 4, 7, 9, 2] Paired List elements : [(4, 1), (5, 9), (6, 7), (2, 4), (8, 2), (9, 9)]
Time complexity: O(n), where n is the length of the input lists.
Auxiliary space: O(n), where n is the length of the input lists.
Method #2: Using list comprehension
Uses similar approach as above method, difference being list comprehension is used as a single linear alternative to solve this problem.
Python3
# Python3 code to demonstrate working of
# Cross Pattern Pairs in List
# Using list comprehension
# function to generate cross pattern pairs
def crossPair(test_list1, test_list2):
# lengths of both lists should be equal
if len(test_list1) != len(test_list2):
return -1
# list comprehension used as one liner alternative
res = [(test_list1[idx], test_list2[idx + 1]) if idx % 2 ==
0 else (test_list1[idx], test_list2[idx - 1]) for idx in range(len(test_list1))]
return res
# initializing lists
input_list1 = [4, 5, 6, 2, 8, 9]
input_list2 = [9, 1, 4, 7, 9, 2]
# printing original lists
print("The original list 1 is : " + str(input_list1))
print("The original list 2 is : " + str(input_list2))
# printing result
print("Paired List elements : ", crossPair(input_list1, input_list2))
Output:
The original list 1 is : [4, 5, 6, 2, 8, 9] The original list 2 is : [9, 1, 4, 7, 9, 2] Paired List elements : [(4, 1), (5, 9), (6, 7), (2, 4), (8, 2), (9, 9)]
Method#3: Using Recursive method.
Python3
# Python3 code to demonstrate working of
# Cross Pattern Pairs in List
# Using recursion function
def crossPair(test_list1, test_list2, idx=0, res=[]):
if idx == len(test_list1):
return res
if idx % 2 == 0:
res.append((test_list1[idx], test_list2[idx + 1]))
else:
res.append((test_list1[idx], test_list2[idx - 1]))
return crossPair(test_list1, test_list2, idx + 1, res)
# initializing lists
input_list1 = [4, 5, 6, 2, 8, 9]
input_list2 = [9, 1, 4, 7, 9, 2]
# printing original lists
print("The original list 1 is : " + str(input_list1))
print("The original list 2 is : " + str(input_list2))
# printing result
print("Paired List elements : ", crossPair(input_list1, input_list2))
#this code contributed by tvsk
OutputThe original list 1 is : [4, 5, 6, 2, 8, 9]
The original list 2 is : [9, 1, 4, 7, 9, 2]
Paired List elements : [(4, 1), (5, 9), (6, 7), (2, 4), (8, 2), (9, 9)]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using numpy():
Algorithm:
- Define a function called crossPair that takes in two lists as arguments.
- Create a list comprehension that iterates through the length of the first list using numpy's arange function
- For each element in the first list, check if its index is even or odd using the modulo operator.
- If the index is even, append a tuple of the current element from the first list and the element at the next index in the second list to a new list.
- If the index is odd, append a tuple of the current element from the first list and the element at the previous index in the second list to the new list.
- Return the new list of paired elements
- Initialize two input lists and print them.
- Call the crossPair function with the two input lists as arguments and print the result.
Python3
import numpy as np
def crossPair(test_list1, test_list2):
return [(test_list1[i], test_list2[i-1] if i%2 else test_list2[i+1]) for i in np.arange(len(test_list1))]
# initializing lists
input_list1 = [4, 5, 6, 2, 8, 9]
input_list2 = [9, 1, 4, 7, 9, 2]
# printing original lists
print("The original list 1 is : " + str(input_list1))
print("The original list 2 is : " + str(input_list2))
# printing result
print("Paired List elements : ", crossPair(input_list1, input_list2))
#This code is contributed by Jyothi pinjala
Output:
The original list 1 is : [4, 5, 6, 2, 8, 9]
The original list 2 is : [9, 1, 4, 7, 9, 2]
Paired List elements : [(4, 1), (5, 9), (6, 7), (2, 4), (8, 2), (9, 9)]
Time Complexity: O(n), where n is the length of the input list. This is because the algorithm iterates through each element of the input list once.
Space Complexity: O(n), where n is the length of the input list. This is because the algorithm creates a new list to store the paired elements, which will be the same length as the input list.
Method 5: Using the map function and a lambda function
Step-by-step approach:
- Use the built-in map function to apply a lambda function to the two input lists simultaneously.
- The lambda function should take two arguments, one from each list, and return a tuple with the elements in the cross pattern.
- Use the list function to convert the map object into a list of tuples.
- Return the list of paired elements.
Python3
def crossPair(test_list1, test_list2):
pairs = list(map(lambda x, y: (x, test_list2[test_list1.index(x)+1]) if test_list1.index(x) % 2 == 0 else (x, test_list2[test_list1.index(x)-1]), test_list1, test_list2))
return pairs
# initializing lists
input_list1 = [4, 5, 6, 2, 8, 9]
input_list2 = [9, 1, 4, 7, 9, 2]
# printing original lists
print("The original list 1 is : " + str(input_list1))
print("The original list 2 is : " + str(input_list2))
# printing result
print("Paired List elements : ", crossPair(input_list1, input_list2))
OutputThe original list 1 is : [4, 5, 6, 2, 8, 9]
The original list 2 is : [9, 1, 4, 7, 9, 2]
Paired List elements : [(4, 1), (5, 9), (6, 7), (2, 4), (8, 2), (9, 9)]
Time complexity: O(n), where n is the length of the input lists, as it requires iterating through both lists.
Auxiliary space: O(n) to store the list of paired elements.
Similar Reads
Python Tutorial | Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read