Pythn
Pythn

Reputation: 171

How do I check if all elements fall in one group?

I have different product groups, let's say toys, clothes and food. When I get a series (or list) of products I want to know if they all fall in one group or if I have products from a few groups.

Let's make an example:

toys=['Car', 'Teddy Bear', 'Doll']
food=['Banana', 'Cola', 'Bread', 'Milk']

So when I get ['Cola', 'Milk'] I want it to return True (they all fall in food) and when I get ['Milk', 'Banana', 'Car'] I want it to return False (contains products of both toys AND food).

Is there a way to check this other than looping trough all my groups and checking one by one if all products are in that specific group?

Thank you!

Upvotes: 2

Views: 65

Answers (3)

Marios Mitalidis
Marios Mitalidis

Reputation: 118

You could use the set data structure in Python.

  • For each group, check if your input list is a subset.
  • Then verify that it is subset of exactly one group.
toys=['Car', 'Teddy Bear', 'Doll']
food=['Banana', 'Cola', 'Bread', 'Milk']

def is_in_one_group(my_list):
    belongs_in_group = [set(my_list).issubset(toys), set(my_list).issubset(food)]
    return sum(belongs_in_group) == 1


is_in_one_group(['Cola', 'Milk'])
# True

is_in_one_group(['Milk', 'Banana', 'Car'])
# False

is_in_one_group([])
# False

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195543

This is essentially a set operation. You can convert the toys and food to sets and then use set.intersection. For example:

toys = ["Car", "Teddy Bear", "Doll"]
food = ["Banana", "Cola", "Bread", "Milk"]

toys, food = set(toys), set(food)


def is_only_one_group(l):
    return bool(toys.intersection(l)) + bool(food.intersection(l)) == 1


print(is_only_one_group(["Milk", "Banana", "Car"]))
print(is_only_one_group(["Cola", "Milk"]))

Prints:

False
True

Upvotes: 2

Mustafa Aydın
Mustafa Aydın

Reputation: 18315

You can build dictionaries out of your lists such that entries of the lists are the keys and values are the name of the list they belong to. Then we can map the items in the new list and check if the number of unique elements is 1 or not:

toys_dict = dict.fromkeys(toys, "toys")
food_dict = dict.fromkeys(food, "food")

combined_dict = {**toys_dict, **food_dict}

def is_only_one_group(new_list):
    return len(set(combined_dict[val] for val in new_list)) == 1

using as

>>> is_only_one_group(["Cola", "Milk"])
True

>>> is_only_one_group(["Milk", "Banana", "Car"])
False

Upvotes: 1

Related Questions