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

后端 未结 7 2448
醉话见心
醉话见心 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:44

    Might that do the trick?

    def getAllCombinations(listOfLists):
        if len(listOfLists) == 1:
            return [str(x) for x in listOfLists[0]]
    
        result = set()
        head, tail = listOfLists[0], listOfLists[1:]
    
        tailCombs = getAllCombinations(tail)
        for elem in head:
            for tc in tailCombs:
                result.add(str(elem) + tc)
        return result
    
    v = [1, 'a']
    w = [1, 'b']
    x = [1, 'c']
    y = [1, 'd']
    z = [1, 'e']
    
    >>> print getAllCombinations([v, w, x, y, z])
    set(['111de', 'abc11', 'a1c1e', 'a111e', '11c11', 'ab11e', '1bc11', 'ab1d1', 'a1cd1', '1b1de', 'a11d1', '11111', '1b111', '11cd1', 'abcd1', '1bcde', 'ab111', '1bc1e', 'abc1e', '111d1', 'a1111', '11c1e', 'a1c11', '11cde', '1b11e', '1bcd1', 'abcde', 'a1cde', '1b1d1', 'a11de', 'ab1de', '1111e'])
    

提交回复
热议问题