Return the cross product of a list of lists

后端 未结 4 2154
攒了一身酷
攒了一身酷 2021-01-17 09:06

Given a list of size n, Write a program that returns all possible combination of elements contained in each list.

Example:

  • List A = \"x, z\"
4条回答
  •  余生分开走
    2021-01-17 09:28

    You do not need recursion. All you need to do is build up a set of intermediate solutions. Here is a non-recursive solution in Python:

    # This does NOT use recursion!
    def all_comb(list_of_lists):
        # We start with a list of just the empty set.
        answer = [[]]
        for list in list_of_lists:
            # new_answer will be the list of combinations including this one.
            new_answer = []
            # Build up the new answer.
            for thing in list:
                for prev_list in answer:
                    new_answer.append(prev_list + [thing])
            # Replace the old answer with the new one.
            answer = new_answer
        # We now have all combinations of all lists.
        return answer
    
    # Demonstration that it works.    
    for comb in all_comb([["x", "y"], ["a", "b", "c"], ["o", "p"]]):
        print(" ".join(comb))
    

提交回复
热议问题