Home > Blockchain >  Write a Python program which takes two list as input and returns True if they have at least 3 common
Write a Python program which takes two list as input and returns True if they have at least 3 common

Time:08-13

I am not able to covert list to set and also how to compare 3 elemnts in list

    a_set = set(a)
    b_set = set(b)
    if len(a_set.intersection(b_set)) > 3:
        return True
    return False
a = [10,20,'Python', 10.20, 10 20j, [10,20,30], (10,20,30)]
b = [(10,20,30),1,20 3j,100.2, 10 20j, [10,20,30],'Python']
print(common_ele(a, b))

CodePudding user response:

def commonElement(a: list, b: list):
    common = 0
    for i in a:
        if i in b:
            common  = 1
    if common > 3:
        return True

a = [10,20,'Python', 10.20, 10 20j, [10,20,30], (10,20,30)]
b = [(10,20,30),1,20 3j,100.2, 10 20j, [10,20,30],'Python']
print(commonElement(a, b))
True

The common elements are:

Python
(10 20j)
[10, 20, 30]
(10, 20, 30)

CodePudding user response:

You could define a helper function for converting the lists into sets:

import collections
from typing import Union


def make_into_set(xs: list[Union[int, str, float, complex, list[int], tuple[int, ...]]]) \
       -> list[Union[int, str, float, complex, tuple[int, ...]]]:
    return {x if isinstance(x, collections.abc.Hashable) else str(x) for x in xs}


def common_ele(a: list[Union[int, str, float, complex, list[int], tuple[int, ...]]],
               b: list[Union[int, str, float, complex, list[int], tuple[int, ...]]]) -> bool:
    a_set = make_into_set(a)
    b_set = make_into_set(b)
    if len(a_set.intersection(b_set)) > 3:
        return True
    return False


a = [10, 20, 'Python', 10.20, 10 20j, [10, 20, 30], (10, 20, 30)]
b = [(10, 20, 30), 1, 20 3j, 100.2, 10 20j, [10, 20, 30], 'Python']
print(common_ele(a, b))

Output:

True

CodePudding user response:

def check(list1, list2):
    same = 0
    for element1 in list1:
        for element2 in list2:
            if element1 == element2:
                same  = 1
    return True if same>=3 else False
  • Related