Python 编程训练7:树实现:increment & square

Python 编程训练7:树实现:increment & square

  • 树 --> object
  • 面向对象设计方法

树 --> object

Python 编程训练7:树实现:increment & square_第1张图片

面向对象设计方法

def increment(n):
    return n+1

def square(n):
    return n**2

class Node:
    def __init__(self, parent, action, answer):
        self.parent = parent
        self.action = action
        self.answer = answer

    def path(self):
        if self.parent == None:
            return [(self.action, self.answer)]
        else:
            return self.parent.path() + [(self.action, self.answer)]

def findSequence3(initial, goal):
    q = [Node(None, None, 1)]
    while q:
        parent = q.pop(0)
        for (a, r) in [('increment', increment), ('square', square)]:
            newNode = Node(parent, a, r(parent.answer))
            if newNode.answer == goal:
                return newNode.path()
            else:
                q.append(newNode)
    return None

def testFindSequence3():
    answer = findSequence3(1,100)
    print('answer =',answer)

你可能感兴趣的:(Python 编程训练7:树实现:increment & square)