Cprod -- (writing this: itertools.product([0, 1], repeat=N )

HenHanna HenHanna at devnull.tb
Tue May 21 15:14:03 EDT 2024


How can i write this function Cprod (Cartesian Product) simply?

                 (writing this out: itertools.product([0, 1], repeat=N )

The value can be a list or a Tuple.

                 cprod([0, 1], 1) => ((0) (1))

                 cprod([0, 1], 2) => ((0,0) (0,1) (1,0) (1,1))



This works:

    def cprod(x, c):
         if c==1: return [[i] for i in x]
         Sub= cprod(x, c-1)
         return [i  for F in x   for i in [[F]+R for R in Sub]]


---------- Is there another way to write [F]+R ???

                Other ways to improve it?


More information about the Python-list mailing list