打印递归步骤

时间:2016-01-24 11:39:19

标签: python python-2.7 recursion printing

我想打印我的程序所做的步骤,并将这些步骤放在一个列表中。但我无法弄清楚为什么我的代码打印错误的输出。我是编程的新手,我希望索莫可以提供帮助。这是我的代码:

r=[]
listOfsteps = []
j = 0

class Main(object):
    def __init__(self):
        i=0
        while i != 1:
            self.method(r, j)
            i+=1

    def method(self, r, j):

        r.append(j)
        listOfsteps.append(r)
        j+=1
        if j ==5:
            return "stop"
        print r
        print "ListOfSteps", listOfsteps
        return self.method(r, j)

Main()

立即输出:

[0]
ListOfSteps [[0]]
[0, 1]
ListOfSteps [[0, 1], [0, 1]]
[0, 1, 2]
ListOfSteps [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
[0, 1, 2, 3]
ListOfSteps [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]

我想要的输出:

[0]
ListOfSteps [[0]]
[0, 1]
ListOfSteps [[0], [0, 1]]
[0, 1, 2]
ListOfSteps [[0], [0, 1], [0, 1, 2]]
[0, 1, 2, 3]
ListOfSteps [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]

2 个答案:

答案 0 :(得分:3)

使用:

listOfsteps.append(list(r))

而不是:

listOfsteps.append(r)

在您的版本中附加对r的引用,并在下一次迭代中更改r,以便您存储的引用受到影响。您需要复制要追加的列表。

您也可以使用 copy 来执行此操作。

答案 1 :(得分:0)

r=[]
listOfsteps = []
j = 0

class Main(object): 

 def __init__(self):
       #you don't need loop while for your example 
        self.method(r, j)

    def method(self, r, j):

        r.append(j)
        # append only the steps index
        #you don't need to add whole list for every step
        listOfsteps.append(j)
        j+=1
        if j == 5:
            return "stop"
        print r
        #to print your step with your output that you want use this loop
        l = [listOfsteps[:i+1] for i in range(len(listOfsteps))]
        print "ListOfSteps", l

        return self.method(r, j)

Main()
相关问题