【问题标题】:Create a Tree of Object Recursively (Python)递归创建对象树(Python)
【发布时间】:2021-12-12 09:15:21
【问题描述】:

我想创建一个名为 State 的对象树。

每个州都有一个包含 4 个机器人的列表,每个州都有不同的机器人坐标。 目标是创建一个将由广度优先搜索算法解决的图。 (原来的游戏是 RicochetRobot 可能你们都知道)。

class State: 
  
    
    def __init__(self,parent,childs,robots,cpt,):
        self.parent = parent
        self.childs = childs
        self.robots = robots
        self.cpt = cpt

我创建了一个函数 create_child 来执行此操作

 def create_child(self,depth):
        #UP
        #Depth is the tree height
        if depth==0:
            print("STOP")
            return
        else : 
      
            for i in range(4):
            
                #Copying the robots of the current object 
                temp = copy.deepcopy(self.robots)
            
            
                
                
                #Getting robot to move index
                temp_robot = temp[i]
            
                #removing this robot from the list
                temp.pop(i)
        
                
                #Moving up the robot and inserting it in the list
                #Moving up is a simple function which increment the y of the robot
                temp.insert(i,moving_up(temp_robot,create_board(init_robot())))
            
                
                
                #Adding a new child into childs list
                self.childs.append(State(self,self.childs,temp,self.cpt+1))
            
            #Decrementing the depth
            depth-=1
            #Recursivity
            for child in self.childs:
                child.create_child(depth)

我的问题是,当 depth = 0 时,它打印 STOP,但它不返回 None,并且函数继续运行。 有谁知道它来自哪里? 另外,如果您能就如何以更简单的方式制作我的树提供建议,那就太好了。

【问题讨论】:

  • 确实返回None。这不会阻止 prior 递归调用继续进行。想象一下,如果您有多个函数副本,例如create_child0create_child1 等,除了名称之外,每个副本都是相同的,并且您总是调用create_child0,而当您传递的depth 将是正好是 0,当深度正好是 1 时调用 create_child1,等等。如果你有那个代码,你会看到你的方法有什么问题吗?递归以同样的方式工作
  • 是的,我想我明白了,根据你给我的解释,这是否意味着在我的代码中,我总是深入但我永远不会回去?就像我使用您的示例一样,这是否意味着,例如,当深度为 3 时,它将调用 create_child3 但它永远不会回到 create_child2 来停止它?

标签: python graph breadth-first-search


【解决方案1】:

好吧,我想我找到了解决办法,就是这样:

depth = 1
parent = Initial_State
for j in range(depth):
   
    for i in range(len(parent.childs)-1):
        parent.childs[i].create_child()
    parent = parent.childs[i]

它似乎正在工作。我不再使用递归,我以一种更迭代的方式在函数之外进行,看起来不错。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2020-05-30
    • 2018-09-21
    • 1970-01-01
    相关资源
    最近更新 更多