Getting all combinations of a string and its substrings

后端 未结 4 1757
心在旅途
心在旅途 2020-12-03 05:32

I\'ve seen many questions on getting all the possible substrings (i.e., adjacent sets of characters), but none on generating all possible strings including the combinations

4条回答
  •  囚心锁ツ
    2020-12-03 06:06

    This is a fun exercise. I think other answers may use itertools.product or itertools.combinations. But just for fun, you can also do this recursively with something like

    def subs(string, ret=['']):
        if len(string) == 0:
            return ret
        head, tail = string[0], string[1:]
        ret = ret + list(map(lambda x: x+head, ret))
        return subs(tail, ret)
    
    subs('abc')
    # returns ['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
    

提交回复
热议问题