w3resource

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.



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Inverts a dictionary with non-unique hashable values:

Example:

def tips_collect_dictionary(obj):
  inv_obj = {}
  for key, value in obj.items():
    inv_obj.setdefault(value, list()).append(key)
  return inv_obj
ages = {
  "Owen": 25,
  "Jhon": 25,
  "Pepe": 15,
}
print(tips_collect_dictionary(ages))

Output:

{25: ['Owen', 'Jhon'], 15: ['Pepe']}

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook