Python for making combinations problem

We remembered the combination and formula of why it is important and when it use.

You use combinations when you want to explore all possible subsets of a certain length from a given set or list, where the order of elements does not matter

\[\binom nk = \frac{n!}{k!(n-k)!} \]

as we can find all the possible combinations in terms of code where we can use the itertools module and just like a cartesian product 

Example 1.

food = ['Strawberry','Cereals','Pasta']
non_heme_iron = ['berries','tomato sauce']
bestCombination = [(food, other) for food in food for other in non_heme_iron]
print(bestCombination)

OutPut: [('Strawberry', 'berries'), ('Strawberry', 'tomato sauce'),
('Cereals', 'berries'), ('Cereals', 'tomato sauce'), ('Pasta', 'berries'),
('Pasta', 'tomato sauce')]



Example 2 with the help of itertools module and product method

from itertools import product
food = ['Strawberry', 'Cereals', 'Pasta']
non_heme_iron = ['berries', 'tomato sauce']
# Generate all possible pairs
pairs = list(product(food, non_heme_iron))
print(pairs)

OutPut:
[('Strawberry', 'berries'), ('Strawberry', 'tomato sauce'), ('Cereals', 'berries'),
('Cereals', 'tomato sauce'), ('Pasta', 'berries'), ('Pasta', 'tomato sauce')]


Verification Using Python:We can verify this by using the itertools.combinations function in Python

from itertools import combinations
food = ['Strawberry', 'Cereals', 'Pasta']
non_heme_iron = ['berries', 'tomato sauce']
all_items = food + non_heme_iron
combinations_of_2 = list(combinations(all_items, 2))
print(combinations_of_2)
print(f"Number of combinations: {len(combinations_of_2)}")

output :
[('Strawberry', 'Cereals'), ('Strawberry', 'Pasta'),
('Strawberry', 'berries'), ('Strawberry', 'tomato sauce'),
('Cereals', 'Pasta'), ('Cereals', 'berries'), ('Cereals', 'tomato sauce'),
('Pasta', 'berries'), ('Pasta', 'tomato sauce'), ('berries', 'tomato sauce')] Number of combinations: 10


The total number of elements n in the combined list is 5. Let's choose k = 2  putting the value in the above formula

\[\binom 52 = \frac{5!}{2!(5-2)!} \]

\[\Rightarrow \binom 52 = \frac{5 \times 4 \times 3 \times 2 \times 1}{2 \times 1 (3 \times 2 \times 1)} \]

\[\Rightarrow Number\; of \;combinations \; \ = 10 \;hence \; proved \]


Comments