Python get all permutations of numbers

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

提交回复
热议问题