我们构造这样一个游戏:
比如:1 到 5
1 increment 2
2 square 4
4 increment 5
共需要4步,操作序列:increment square increment
如何输出从 a 到 b 的操作序列
def increment(n):
return n+1
def square(n):
return n**2
def findSequence(initial, goal):
# root node
candidates = [(str(initial), initial)]
# loop
for i in range(1, goal - initial + 1):
newCandidates = []
for (action, result) in candidates:
for (a, r) in [(' increment', increment), (' square', square)]:
newCandidates.append((action + a, r(result)))
print (i, ': ', newCandidates[-1])
if newCandidates[-1][1] == goal:
return newCandidates[-1]
candidates = newCandidates
def increment(n):
return n+1
def square(n):
return n**2
def apply(opList, arg):
if len(opList) == 0:
return arg
else:
return apply(opList[1:], opList[0](arg))
def addLevel(opList, fctList):
return [x+[y] for y in fctList for x in opList]
def findSequence2(initial, goal):
opList = [[]]
for i in range(1, goal-initial+1):
opList = addLevel(opList, [increment, square])
for seq in opList:
if apply(seq, initial) == goal:
return seq
opList 存放操作序列:比如[increment, increment, square, increment]
arg 存放初始参数
递归调用,比如: 传入参数opList = [increment, increment, square, increment]; arg = 10
apply(opList, 1) # opList = [increment, increment, square, increment]; arg = 1
apply(opList, increment(1)) # opList = [increment, square, increment]; arg = 2
apply(opList, increment(2)) # opList = [square, increment]; arg = 3
apply(opList, square(3)) # opList = [increment]; arg = 9
apply(opList, increment(9)) # opList = []; arg = 10
return 10
return 10
return 10
return 10
return 10
用于生成操作序列,该操作序列会使用 apply(opList, arg) 作用在一个 arg 初始参数上。
其中:x+[y] for y in fctList for x in opList
两层循环,外层参数为y,内层参数为x
返回值是 x+[y]
fctList 用于记录每个原子操作,比如这里是 [increment, square]