我有2个水壶的问题。 初始状态为[0,0],每个壶的容量为[4,9],目标状态为[0,6] 合法动作:将壶1或壶2填到最后,将空壶1或壶2和可怜的壶放入另一壶中。
import search #get the interface
import sys
sys.setrecursionlimit(5000)
class two_jugs(search.Nodes):
#return the starting state vessel 1: 0, vessel 2: 0
def start(self):
return [0,0]
#returns true if node is equal to goal node
def goal(self,node):
return node ==(0,6)
#yields the successors of the configuration indicated by node
def succ(self,node):
# set capacities for vessel 1: 4, vessel 2 : 9
c = [4,9];
#stop at second last
for i in range(len(node)-1):
#create a safety copy
new_node = node[:]
#fill vessel 1
if new_node[i]<=0:
new_node[i]=c[i]
print new_node
#fill vessel 2
if new_node[i+1]<=0:
new_node[i+1]=c[i+1]
print new_node
#dump vessel i+1
if (new_node[i+1]>0):
new_node[i+1]=0
print new_node
#poor vessel i to vessel i+1
if (new_node[i+1]<c[i+1] and new_node[i]>0):
#calculate the difference
d = min(new_node[i],c[i+1]-new_node[i+1])
new_node[i]= new_node[i]-d
new_node[i+1]= new_node[i+1]+d
print new_node
#dump vessel i
if (new_node[i]>0):
new_node[i]=0
print new_node
#poor vessel i+1 to vessel 1
if (new_node[i]<c[i] and new_node[i+1]>0):
#calculate the difference
d = min(new_node[i+1],c[i]-new_node[i])
#set new node
new_node[i+1]= new_node[i+1]-d
new_node[i]= new_node[i]+d
yield new_node
print new_node
问题是,由于我已经宣布了所有法律行动,为什么我的计划只返回一项法律行动的结果?例如,当我运行程序时从起始状态[0,0]返回[4,0],[0,4],[0,9]和其他可能的结果,直到递归停止但不是我的目标状态。 我错过了什么?
breadth_first_search类:
def breadth_first_search(problem, candidates):
if not candidates: return
# make sure there is something in the candidate list
# I am modifying ’candidates’ list here.
# Why don’t I need to copy?
c = candidates.pop(0) # pop from front
node = c[-1] # must exist
if problem.goal(node): return c
# base case
succ = [s for s in problem.succ(node)]
for s in problem.succ(node):
candidates.append(c + [s])
# 1-step extension
return breadth_first_search(problem, candidates)
搜索课程:
class Nodes:
def succ(self,n):
raise Exception, "Successor undefined"
def start (self):
raise Exception, "Start undefined"
def goal (self,n):
raise Exception, "Goal undefined"
运行程序的类:
import decant
from breadth_first_search import *
dec = decant.Decant()
print breadth_first_search(dec,[[dec.start()]])
答案 0 :(得分:0)
你的第一个错误是标记班级2jugs
。 python中的变量名(包括类和函数的名称)以及许多其他编程语言都不能以数字开头。因此,请将2jugs
重命名为two_jugs
。
precise rule for identifiers in python是标识符必须以大写(A-Z
),小写(a-z
)或下划线(_
)开头。标识符的以下字符也可以包含数字(0-9
)。 (该规则在Backus-Naur form)中指定。