I am trying to write a python 3.6 command-line program that accepts as arguments one or more lists and then returns the cartesian product of those lists, possibly in deduplicated form.
I have it working correctly with one and two list arguments, but I cannot figure out how to make the program correctly handle three or more arguments.
The desired output is the cartesian product that includes every list passed as an argument on the command line.
This is the code I have so far:
def createArgumentParser():
from argparse import ArgumentParser
__parser = ArgumentParser()
__parser.add_argument("list", type=list, nargs="+", help="List(s) to compute the cartesian product of")
__parser.add_argument("-u", "--unique", action="store_true", help="Deduplicate lists so that they become sets of unique elements")
__parser.add_argument("-U", "--Universally_unique", action="store_true", help="Deduplicate the resulting cartesian product so that the final result is a set of unique elements")
return __parser.parse_args()
def cartesianProduct(__unique, __Universally_unique, *__list):
from itertools import product
__cartesianProduct = product([])
if __unique:
__cartesianProduct = product(sorted(set(__list[0])), sorted(set(__list[len(__list)-1])))
else:
__cartesianProduct = product(__list[0], __list[len(__list)-1])
if __Universally_unique:
__cartesianProduct = sorted(set(__cartesianProduct))
for __element in __cartesianProduct:
if __element[0] == __element[1]:
__cartesianProduct.remove(__element)
return __cartesianProduct
def main():
__args = createArgumentParser()
for __element in cartesianProduct(__args.unique, __args.Universally_unique, *__args.list):
print(__element)
Running the program with the command line arguments abc 123 def
returns this:
('a', 'd')
('a', 'e')
('a', 'f')
('b', 'd')
('b', 'e')
('b', 'f')
('c', 'd')
('c', 'e')
('c', 'f')
The 123
part is missing from the cartesian product. How can I fix that?