Python get all permutations of numbers

前端 未结 4 1999
臣服心动
臣服心动 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:10

    I'd use python's itertools, but if you had to implement this yourself, here's code that returns all permutations of a specified size for a list of values.

    Example: values = [1,2,3], size = 2 => [[3, 2], [2, 3], [2, 1], [3, 1], [1, 3], [1, 2]]

    def permutate(values, size):
      return map(lambda p: [values[i] for i in p], permutate_positions(len(values), size))
    
    def permutate_positions(n, size):
      if (n==1):
        return [[n]]
    
      unique = []
      for p in map(lambda perm: perm[:size], [ p[:i-1] + [n-1] + p[i-1:] for p in permutate_positions(n-1, size) for i in range(1, n+1) ]):
        if p not in unique:
          unique.append(p)
    
      return unique
    
    0 讨论(0)
  • 2020-12-17 00:20
    >>> lst = [3, 3, 4]
    >>> import itertools
    >>> set(itertools.permutations(lst))
    {(3, 4, 3), (3, 3, 4), (4, 3, 3)}
    
    0 讨论(0)
  • 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']
    
    0 讨论(0)
  • 2020-12-17 00:32

    You want permutations, not combinations. See: How to generate all permutations of a list in Python

    >>> from itertools import permutations
    >>> [a for a in permutations([3,3,4])]
    [(3, 3, 4), (3, 4, 3), (3, 3, 4), (3, 4, 3), (4, 3, 3), (4, 3, 3)]
    

    Note that it's permuting the two 3's (which is the correct thing mathematically to do), but isn't the same as your example. This will only make a difference if there are duplicated numbers in your list.

    0 讨论(0)
提交回复
热议问题