Dynamically cross-join multiple different-size collections together in Linq (C#)

You could create an extension method like the following: public static class EnumerableExtensions { public static IEnumerable<TValue []> Permutations<TKey, TValue>(this IEnumerable<TKey> keys, Func<TKey, IEnumerable<TValue>> selector) { var keyArray = keys.ToArray(); if (keyArray.Length < 1) yield break; TValue [] values = new TValue[keyArray.Length]; foreach (var array in Permutations(keyArray, 0, selector, values)) yield return array; } static … Read more

How can I make a list of dictionaries according to the Cartesian product of values in a source dictionary (“explode” the dictionary)?

I think you want the Cartesian product, not a permutation, in which case itertools.product can help: >>> from itertools import product >>> d = {‘Color’: [‘Red’, ‘Yellow’], ‘Size’: [‘Small’, ‘Medium’, ‘Large’]} >>> [dict(zip(d, v)) for v in product(*d.values())] [{‘Color’: ‘Red’, ‘Size’: ‘Small’}, {‘Color’: ‘Red’, ‘Size’: ‘Medium’}, {‘Color’: ‘Red’, ‘Size’: ‘Large’}, {‘Color’: ‘Yellow’, ‘Size’: ‘Small’}, {‘Color’: … Read more

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

Iteratively compute the Cartesian product of an arbitrary number of sets

I’ve written a solution that doesn’t require you to fill up a large collection in memory. Unfortunately, the code required is hundreds of lines long. You may have to wait until it appears in the Guava project (https://github.com/google/guava), which I hope will be by the end of the year. Sorry. 🙁 Note that you may … Read more

tech