combinatorics
How can I get “permutations with repetitions/replacement” from a list (Cartesian product of a list with itself)?
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: import itertools x = [1, 2, 3, 4, 5, … Read more
How can I match up permutations of a long list with a shorter list (according to the length of the shorter list)? [duplicate]
The simplest way is to use itertools.product: a = [“foo”, “melon”] b = [True, False] c = list(itertools.product(a, b)) >> [(“foo”, True), (“foo”, False), (“melon”, True), (“melon”, False)]
How can I get pairs of values, where the first is taken from one list and the second from another list? [duplicate]
These are not really “combinations” in the sense of combinatorics. These are rather elements from the Cartesian product of a and b. The function in the standard library to generate these pairs is itertools.product(): for i, j in itertools.product(a, b): # Whatever
Google Interview: Arrangement of Blocks
This is a counting problem, not a construction problem, so we can approach it using recursion. Since the problem has two natural parts, looking from the left and looking from the right, break it up and solve for just one part first. Let b(N, L, R) be the number of solutions, and let f(N, L) … Read more
What does this list permutations implementation in Haskell exactly do?
Sorry about the late answer, it took a bit longer to write down than expected. So, first of all to maximize lazyness in a list function like this there are two goals: Produce as many answers as possible before inspecting the next element of the input list The answers themselves must be lazy, and so … Read more
Set partitions in Python
Since this nice question has been brought back to life, here’s a fresh answer. The problem is solved recursively: If you already have a partition of n-1 elements, how do you use it to partition n elements? Either place the n‘th element in one of the existing subsets, or add it as a new, singleton … Read more
How can I print out all possible letter combinations a given phone number can represent?
In Python, iterative: digit_map = { ‘2’: ‘abc’, ‘3’: ‘def’, ‘4’: ‘ghi’, ‘5’: ‘jkl’, ‘6’: ‘mno’, ‘7’: ‘pqrs’, ‘8’: ‘tuv’, ‘9’: ‘wxyz’, } def word_numbers(input): input = str(input) ret = [”] for char in input: letters = digit_map.get(char, ”) ret = [prefix+letter for prefix in ret for letter in letters] return ret ret is a … Read more