Python get all permutations of numbers

前端 未结 4 2013
臣服心动
臣服心动 2020-12-16 23:39

I\'m trying to display all possible permutations of a list of numbers, for example if I have 334 I want to get:

3 3 4
3 4 3
4 3 3

I need to

4条回答
  •  死守一世寂寞
    2020-12-17 00:26

    without itertools

    def permute(LIST):
        length=len(LIST)
        if length <= 1:
            yield LIST
        else:
            for n in range(0,length):
                 for end in permute( LIST[:n] + LIST[n+1:] ):
                     yield [ LIST[n] ] + end
    
    for x in permute(["3","3","4"]):
        print x
    

    output

    $ ./python.py
    ['3', '3', '4']
    ['3', '4', '3']
    ['3', '3', '4']
    ['3', '4', '3']
    ['4', '3', '3']
    ['4', '3', '3']
    

提交回复
热议问题