【问题标题】:Permutations in Python without repetitionsPython中没有重复的排列
【发布时间】:2015-01-19 23:09:55
【问题描述】:

我正在开发一个程序,该程序从用户那里获取一个列表作为输入,并且应该打印该列表的所有排列。 问题是我得到的输出是列表中数字的重复,所以这些在技术上并不是真正的排列。我怎样才能避免这种情况? (请注意,如果用户在列表中两次输入相同的数字,这不会算作重复)所以基本上我不能在每个组合中重复相同的索引。

注意:我不允许使用内置的 permutations 函数。

这是我到目前为止所做的:

def permutation(numberList,array,place):
    if (place==len(numberList)):
        print array
    else:
        i=0
        while (i < len(numberList)):
            array.append(numberList[i])
            permutation(numberList,array,place+1)
            array.pop()
            i+=1

def scanList():
    numberList=[];
    number=input()
    #keep scanning for numbers for the list
    while(number!=0):
       numberList.append(number)
       number=input()
    return numberList


permutation(scanList(),[],0)

1 2 3 0 的输出例如:

[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 2, 1]
[1, 2, 2]
[1, 2, 3]
[1, 3, 1]
[1, 3, 2]
[1, 3, 3]
[2, 1, 1]
[2, 1, 2]
[2, 1, 3]
[2, 2, 1]
[2, 2, 2]
[2, 2, 3]
[2, 3, 1]
[2, 3, 2]
[2, 3, 3]
[3, 1, 1]
[3, 1, 2]
[3, 1, 3]
[3, 2, 1]
[3, 2, 2]
[3, 2, 3]
[3, 3, 1]
[3, 3, 2]
[3, 3, 3]

谢谢。

【问题讨论】:

  • 置换索引而不是数字。
  • 这是什么意思?我可以在代码中更改什么来做到这一点?
  • 将每个排列作为元组添加到集合中,并每次检查集合。
  • 说你的数组有 3 个元素。生成 [0, 1, 2] 的排列(参见stackoverflow.com/questions/104420/…)。然后对于每个排列 P 打印 numberList[P[0], P[1], P[2]]。你明白了吗?
  • 不是真的,对不起:(

标签: python algorithm permutation


【解决方案1】:

一个简单的解决方案是使用set 来了解您已经使用了哪些号码以及您没有使用哪些号码:

def permutation(numberList,array,visited,place):
    if (place==len(numberList)):
        print array
    else:
        i=0
        while (i < len(numberList)):
            if i not in visited:
                visited.add(i)
                array.append(numberList[i])
                permutation(numberList,array,visited,place+1)
                array.pop()
                visited.remove(i)
            i+=1

def scanList():
    numberList=[];
    number=input()
    #keep scanning for numbers for the list
    while(number!=0):
       numberList.append(number)
       number=input()
    return numberList


permutation(scanList(),[],set(), 0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    相关资源
    最近更新 更多