w3resource

Python: Generate all the combinations with repetitions of k types of things taken n at a time


13. Color Combinations with Repetition

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')]

For more Practice: Solve these Related Problems:

  • Write a Python program to select a specified number of colors from three different options and generate all possible combinations with repetition allowed.
  • Write a Python program to create an iterator that produces combinations of colors with repetition and then filters combinations that have adjacent identical colors.
  • Write a Python program to generate repeated combinations from three color sets and then map a function to sort each combination alphabetically.
  • Write a Python program to compute all combinations with repetition from three colors and then remove combinations that do not meet a given pattern.

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.



Follow us on Facebook and Twitter for latest update.