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

    From HenHanna@21:1/5 to All on Tue May 21 12:14:03 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?

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From dn@21:1/5 to HenHanna via Python-list on Wed May 22 10:44:44 2024
    On 22/05/24 07:14, HenHanna via Python-list wrote:

    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?

    https://python.readthedocs.io/en/stable/library/itertools.html#itertools.product

    --
    Regards,
    =dn

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From HenHanna@21:1/5 to All on Wed May 22 05:21:53 2024
    dn wrote:

    On 22/05/24 07:14, HenHanna via Python-list wrote:

    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?

    https://python.readthedocs.io/en/stable/library/itertools.html#itertools.product
    Regards, =dn


    Thank you... That code looks elegant... I'll study it.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)