12
4
Introduction
The Cartesian product of two lists is calculated by iterating over every element in the first and second list and outputting points. This is not a very good definition, so here are some examples: the Cartesian product of [1, 2]
and [3, 4]
is [(1, 3), (1, 4), (2, 3), (2, 4)]
. The product of [1]
and [2]
is [(1, 2)]
. However, no one said you could only use two lists. The product of [1, 2]
, [3, 4]
, and [5, 6]
is [(1, 3, 5), (1, 4, 5), (1, 3, 6), (1, 4, 6), (2, 3, 5), (2, 4, 5), (2, 3, 6), (2, 4, 6)]
.
Challenge
Given a number of lists, your program must output the Cartesian product of the lists given.
- You can assume that there will always be more than 1 list, and that each list will have the same length. No list will ever be empty. If your language has no method of stdin, you may take input from command line arguments or a variable.
- Your program must output the Cartesian product of all the input lists. If your language has no stdout, you may store output in a variable or as a return value. The output should be a list of lists, or any other iterable type.
Example I/O
Input:
[1, 2] [3, 4]
Output:[(1, 3), (1, 4), (2, 3), (2, 4)]
Input:
[1, 2] [3, 4] [5, 6]
Output:[(1, 3, 5), (1, 4, 5), (1, 3, 6), (1, 4, 6), (2, 3, 5), (2, 4, 5), (2, 3, 6), (2, 4, 6)]
Input:
[1, 2, 3] [4, 5, 6]
Output:[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
Rules
This is code-golf so shortest answer in bytes wins!
6boring answer:
itertools.product
in python – Quintec – 2019-11-16T17:54:50.827Related, related. – Digital Trauma – 2019-11-16T23:13:10.073
2If your language has no method of stdin, you may take input from command line arguments or a variable I suggest you allow command-line inputs without any condition. See here – Luis Mendo – 2019-11-17T03:12:29.093
Does order matter among the output lists? – xnor – 2019-11-17T05:45:58.203
Order does not matter @xnor. – sugarfi – 2019-11-17T13:18:01.370
Is it mandatory to have an output in the format
[[a,b,c],[a,c,b],...]
(in any order), or are other formats also allowed? The two Japt answers output as[a,b,c,a,c,b,...]
and[[[a,b],c], [[a,c],b], ...]
instead for example (not sure if this is a valid output)? – Kevin Cruijssen – 2019-11-18T12:34:45.0101No, the format described is not mandatory @KevinCruijssen – sugarfi – 2019-11-18T22:09:14.790