Is there an algorithm to find unique combinations of 2 lists? 5 lists?

后端 未结 7 2449
醉话见心
醉话见心 2020-12-20 06:29

I have N Lists I\'d like to find unique combinations of. I\'ve written it out on my whiteboard and it all seems to have a pattern, I just haven\'t found it

7条回答
  •  渐次进展
    2020-12-20 06:49

    I think another answer is in order, to respond to this:

    I've written it out on my whiteboard and it all seems to have a pattern, I just haven't found it yet.

    There is a pattern.

    Suppose you have just two lists to combine. You can find all the combinations by making a grid.

           black        blue
         +------------+------------+
    coat | black coat | blue coat  |
         +------------+------------+
    hat  | black hat  | blue hat   |
         +------------+------------+
    

    As you can see, there are 2*2 combinations. If there were 30 colors and 14 kinds of clothing, you would have 30 * 14 = 420 combinations.

    The pattern continues as you add more lists. Instead of a 2-dimensional rectangle, you get an 3-dimensional array of boxes, or ultimately an n-dimensional hyperrectangle. Regardless, the total number of combinations is always the product of the lengths of all the lists.

    If you know how many lists you have, nested loops are a natural way to make all combinations.

    for color in colors:
        for kind in kinds:
            print color, kind  # "black coat", "black hat", etc.
    

    If the lists are in dictionary order to start with, and there are no duplicates, the output will also be in dictionary order.

提交回复
热议问题