Python: Generate all the combinations with repetitions of k types of things taken n at a time
Python Itertools: Exercise-13 with Solution
Write a Python program that will select a specified number of colours from three different colours, and then generate all the combinations with repetitions.
Sample Solution:
Python Code:
from itertools import combinations_with_replacement
def combinations_colors(l, n):
return combinations_with_replacement(l,n)
l = ["Red","Green","Blue"]
print("Original List: ",l)
n=1
print("\nn = 1")
print(list(combinations_colors(l, n)))
n=2
print("\nn = 2")
print(list(combinations_colors(l, n)))
n=3
print("\nn = 3")
print(list(combinations_colors(l, n)))
Sample Output:
Original List: ['Red', 'Green', 'Blue'] n = 1 [('Red',), ('Green',), ('Blue',)] n = 2 [('Red', 'Red'), ('Red', 'Green'), ('Red', 'Blue'), ('Green', 'Green'), ('Green', 'Blue'), ('Blue', 'Blue')] n = 3 [('Red', 'Red', 'Red'), ('Red', 'Red', 'Green'), ('Red', 'Red', 'Blue'), ('Red', 'Green', 'Green'), ('Red', 'Green', 'Blue'), ('Red', 'Blue', 'Blue'), ('Green', 'Green', 'Green'), ('Green', 'Green', 'Blue'), ('Green', 'Blue', 'Blue'), ('Blue', 'Blue', 'Blue')]
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to create Cartesian product of two or more given lists using itertools.
Next: Write a Python program generate permutations of specified elements, drawn from specified values.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/itertools/python-itertools-exercise-13.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics