Python recursion permutations

前端 未结 9 1086
自闭症患者
自闭症患者 2020-11-27 19:24

Im having trouble trying to make a permutation code with recursion. This is suppose to return a list back to the use with all the posible position for each letter. so for t

9条回答
  •  旧时难觅i
    2020-11-27 19:53

    You can use a function that iterates an index through the list, and yield a list consisting of the value at the index followed by the permutations of the rest of the list values. Below is an example using features from Python 3.5+:

    def permutations(s):
        if not s:
            yield []
        yield from ([s[i], *p] for i in range(len(s)) for p in permutations(s[:i] + s[i + 1:]))
    

    so that list(permutations('abc')) returns:

    [['a', 'b', 'c'],
     ['a', 'c', 'b'],
     ['b', 'a', 'c'],
     ['b', 'c', 'a'],
     ['c', 'a', 'b'],
     ['c', 'b', 'a']]
    

提交回复
热议问题