Question or problem about Python programming:
I know about itertools, but it seems it can only generate permutations without repetitions.
For example, I’d like to generate all possible dice rolls for 2 dice. So I need all permutations of size 2 of [1, 2, 3, 4, 5, 6] including repetitions: (1, 1), (1, 2), (2, 1)… etc
Note that there are n! Permutations and it requires O(n) time to print a a permutation. Note: The above solution prints duplicate permutations if there are repeating characters in input string. Please see below link for a solution that prints only distinct permutations even if there are duplicates in input. Storyist 4 is a powerful writing environment for novelists and screenwriters. With Storyist, you can: Produce submission-ready manuscripts and screenplays. Storyist provides a rich text editor with. Things is the award-winning personal task manager that helps you achieve your goals. This all-new version has been rethought from the ground up: it’s got an all-new design, delightful new interactions, and powerful new features. OS X 10.9 or later (Intel only). Convert video, audio, and image files to different formats, modify them in various ways,.
If possible I don’t want to implement this from scratch
How to solve the problem:
Solution 1:
You are looking for the Cartesian Product.
In mathematics, a Cartesian product (or product set) is the direct product of two sets.
In your case, this would be {1, 2, 3, 4, 5, 6}
x {1, 2, 3, 4, 5, 6}
.itertools
can help you there:
To get a random dice roll (in a totally inefficient way):
Solution 2:
You’re not looking for permutations – you want the Cartesian Product. For this use product from itertools:
Solution 3:
In python 2.7 and 3.1 there is a itertools.combinations_with_replacement
function:
Solution 4:
In this case, a list comprehension is not particularly needed.
Given
Code
Details
Unobviously, Cartesian product can generate subsets of permutations. However, it follows that:
- with replacement: produce all permutations nr via
product
- without replacement: filter from the latter
Permutations with replacement, nr
Permutations without replacement, n!
Consequently, all combinatoric functions could be implemented from product
:
combinations_with_replacement
implemented fromproduct
combinations
implemented frompermutations
, which can be implemented withproduct
(see above)
Solution 5:
I think I found a solution using only lambdas
, map
and reduce
.
Essentially I’m mapping a first lambda function that given a row, iterates the columnns
then this is used as the output of a new lambda function
which is mapped across all the possible rows
and then we reduce all the resulting lists into one.
Permute 2.2 For Macos Operating System
even better
Can also use two different numbers.
Solution 6:
Permute 2.2 For Macos 10.13
First, you’ll want to turn the generator returned by itertools.permutations(list) into a list first. Then secondly, you can use set() to remove duplicates
Something like below: