开发者

Python get all permutations of numbers

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 be able to do this for any set of digits up to about 12 digits long.

I'm sure its probably fairly simple using something like itertools.combinations but I can't quite get the syntax right.

TIA Sam


>>> lst = [3, 3, 4]
>>> import itertools
>>> set(itertools.permutations(lst))
{(3, 4, 3), (3, 3, 4), (4, 3, 3)}


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']


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜