【问题标题】:Permutations of an int list in python using stacks and/or queuespython中使用堆栈和/或队列的int列表的排列
【发布时间】:2018-04-08 10:26:40
【问题描述】:

我正在尝试编写一个方法def permutations(lst),它接受一个整数列表(例如 [1,2,3])并打印它的所有可能排列,不使用递归 .我还必须在此方法中使用堆栈和/或队列。

到目前为止我有:

class Queue:

    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self, item):
        self.items.insert(0,item)

    def dequeue(self):
        return self.items.pop()

    def size(self):
        return len(self.items)

    def __rep__(self):
        return str(self.items)


def permutation(lst):
    temp = [0] * len(lst)
    q = Queue()
    q.enqueue(lst)
    i = 1
    while i < len(lst):
        if temp[i] < i:
            j = temp[i] if i % 2 else 0
            lst[j], lst[i] = lst[i], lst[j]
            q.enqueue(lst)
            temp[i] += 1
            i = 1
        else:
            temp[i] = 0
            i += 1

    return q.__rep__()


l = [1,2,3]
print(permutation(l))

但我得到的输出是: [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1] , [3, 2, 1]]。

但是,当我打印 lst 而不是将其入队时(仅用 print 替换入队行),我得到了正确的输出。 [[1, 2, 3], [2, 1, 3],[3, 1, 2],[1, 3, 2],[2, 3, 1],[3, 2, 1]]。

如何修改我的代码以使用入队?任何建议表示赞赏。

【问题讨论】:

  • 大概这是一个不允许您使用内置排列功能的分配?
  • 可以使用标准的collections.dqueue类。

标签: python stack queue permutation


【解决方案1】:

问题

问题出在enqueue 中的列表引用中:您有六个对同一列表的引用。每次更改一个元素时,都会更改所有元素。在中间点打印q,你会看到效果:

    else:
        temp[i] = 0
        i += 1
    print ("temp", temp)
    print ("lst", lst)
    print("q", q.__rep__())

输出:

temp [0, 1, 0]
lst [2, 1, 3]
q [[2, 1, 3], [2, 1, 3]]
temp [0, 0, 0]
lst [2, 1, 3]
q [[2, 1, 3], [2, 1, 3]]
...
temp [0, 0, 2]
lst [3, 2, 1]
q [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
temp [0, 0, 0]
lst [3, 2, 1]
q [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
[[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]

相反,在您入队时制作列表的副本:

def enqueue(self, item):
    self.items.insert(0, item[:])

这将为您提供所需的输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2015-11-16
    • 2013-09-18
    • 2010-11-20
    • 1970-01-01
    相关资源
    最近更新 更多