Python Program to Find the Common Elements in the N Sets

 

Common Elements in N Sets

Write a program to find the common elements in the N sets.

Input

The first line of input will contain a positive integer (N).
The next N lines will contain space-separated integers, denoting the elements of each set.

Output

The output should be a single line containing the list of common elements in N sets sorted in ascending order.

Explanation

For example, if the given N is 3, read inputs in the next three lines. If the given three strings are as the following.
2 4 6 8 10
48 10 12 16
5 10 15 20

As 10 is common in all three sets, the output should be

[10]

Sample Input 1
24 6 8 10
4 8 10 12 16
5 10 15 20

Sample Output 1
[10]

Code

def convert_string_to_int(list_a):
    new_list = []
    for item in list_a:
        num = int(item)
        new_list.append(num)
    return new_list


def get_intersection_of_n_sets(num_set_list):
    result = num_set_list[0]
    for num_set in num_set_list:
        result = result.intersection(num_set)
    return result


n = int(input())
num_set_list = []
for i in range(n):
    values_list = input().split()
    values_list = convert_string_to_int(values_list)
    values_set = set(values_list)
    num_set_list.append(values_set)

result_set = get_intersection_of_n_sets(num_set_list)
result_list = list(result_set)
result_list.sort()
print(result_list)

Input
4
24 6 8 10 12
24 8 12 16 10
2 5 10 12 15 20 4
12 10 4 8

Output
[4, 10, 12]

Comments

Popular posts from this blog

CODING ASSIGNMENT 4

CODING PRACTICE 11 Music Page

CCBP Static Website Coding Assignment 2 Solution | Yoga Page