Home > Net >  How to check if the number is from same group or not
How to check if the number is from same group or not

Time:08-06

List Group Mapper:

a = [[658,659,660],[1217,1218,1219],[1691,1692,1693],[1694,1695,1696]]

should return true only if the the input array is from same group(nested list). if the input arry is from different group it should return false.

input1 = [658] --> True
input2 = [658,659] --> True
input3 = [658,659,660] --> True
input4 = [1217] --> True
input5 = [1217,1218] --> True
input6 = [1217,1218,1219] --> True
input7 = [1217,658] --> False
input8 = [1217,1218,658] --> False
input9 = [658,659,1217] --> False

CodePudding user response:

Try this (inp is your input list, groups your list group mapper):

def check_inp(inp, groups):
    if len(inp) == 0:
        return True
    g = next((group for group in groups if inp[0] in group), [])
    return all(x in g for x in inp)

Examples:

>>> groups = [[658,659,660],[1217,1218,1219],[1691,1692,1693],[1694,1695,1696]]
>>> check_inp([658], groups)
True
>>> check_inp([658, 659], groups)
True
>>> check_inp([658, 659, 660], groups)
True
>>> check_inp([1217], groups)
True
>>> check_inp([1217, 1218], groups)
True
>>> check_inp([1217, 1218, 1219], groups)
True
>>> check_inp([1217, 658], groups)
False
>>> check_inp([1217, 1218, 658], groups)
False
>>> check_inp([658, 659, 1217], groups)
False

Some special cases (input not in groups, and empty input):

>>> check_inp([1], groups)
False
>>> check_inp([], groups)
True

CodePudding user response:

Define a function, where a is your list of groups and i is the input:

def check_input(a, i):
    for g in a:
        if all(x in g for x in i):
            return True
    return False

Example:

a = [[658,659,660],[1217,1218,1219],[1691,1692,1693],[1694,1695,1696]]

input1 = [658]
input2 = [658,659]
input3 = [658,659,660]
input4 = [1217]
input5 = [1217,1218]
input6 = [1217,1218,1219]
input7 = [1217,658]
input8 = [1217,1218,658]
input9 = [658,659,1217]

inputs = [input1, input2, input3, input4, input5, input6, input7, input8, input9]
for i in inputs:
    print(check_input(a, i))

Returns:

True
True
True
True
True
True
False
False
False

Caution handing over an empty list (i=[]) will result in True.

CodePudding user response:

A readable way would be to change inputs to sets and look for subset


def check(list_of_list, a_list):
    gen_of_set = (set(l) for l in list_of_list)
    a_set = set(a_list)
    
    for l in gen_of_set:
        if a_set.issubset(l):
            return True
    return False

Tests:

a = [[658,659,660],[1217,1218,1219],[1691,1692,1693],[1694,1695,1696]]
test_1 = [658,659,1217]
test_2 = [658,659]

check(a, test_1) # False
check(a, test_2) # True
check([], test_1) # False
  • Related