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 to chose specified number of colours from three different colours and 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 Python skills with w3resource's quiz
Python: Tips of the Day
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework