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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join