Hanwool Codes RSS Tag Admin Write Guestbook
2023-02-21 06:13:03

itertools.product() | HackerRank

 

itertools.product() | HackerRank

Find the cartesian product of 2 sets.

www.hackerrank.com

 

Goal

You are given a two lists  A and B. Your task is to compute their cartesian product A x B by using itertools.product()

 

Solution

 

The script you provided utilizes the Python itertools library to generate the Cartesian product of two lists A and B, where each element in A is paired with each element in B.

The resulting pairs are printed to standard output.

The script begins by importing the product function from the itertools library.

The product function generates the Cartesian product of multiple iterables, which in this case are the lists A and B.

Next, the script prompts the user to input the elements of list A and list B.

The input() function takes user input as a string, and the map() function applies the int() function to each element of the resulting string to convert them into integers.

The resulting lists of integers are assigned to the variables A and B, respectively.

The product function is then called with A and B as arguments.

The resulting pairs are stored in the result variable as a list of tuples.

The script then iterates over the result list using a for loop.

The range() function is used to iterate from 0 to the length of result minus 1.

For each iteration, the current tuple in result is printed to standard output with a space separator between its elements. The end parameter of the print() function is set to a single space, so that each printed tuple is followed by a space instead of a newline character.

When the loop reaches the last tuple in result, the end parameter is not set, so the final tuple is printed on its own line.

 

In summary, the script generates the Cartesian product of two lists using the product function from the itertools library and prints the resulting pairs to standard output. This script can be useful in scenarios where it is necessary to combine every element in one list with every element in another list, such as when generating all possible combinations of variables in a simulation.

 

# itertools.product()
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import product

A = list(map(int, input().split()))
B = list(map(int, input().split()))

result = list(product(A,B))

for i in range(len(result)):
    
    if i < len(result) - 1 :
        print(result[i], end=' ')
    else:
        print(result[i])
Hanwool Codes. Designed by 코딩재개발.