Python 水壶问题,无法清空其他两个瓶子
我目前正在解决水壶的问题,几乎已经完成了。我的一个要求第一个(a)瓶有8升水,但其他两个(b和c)是空的。我可以让它让我的第一个得到填补,但不能完成其他条件,让其他两个空。如果我给它一个and运算符(a==8,b==0,c==0),程序就不会运行。注意:DFS正在用于此操作 这是我的节目:Python 水壶问题,无法清空其他两个瓶子,python,python-3.x,water-jug-problem,Python,Python 3.x,Water Jug Problem,我目前正在解决水壶的问题,几乎已经完成了。我的一个要求第一个(a)瓶有8升水,但其他两个(b和c)是空的。我可以让它让我的第一个得到填补,但不能完成其他条件,让其他两个空。如果我给它一个and运算符(a==8,b==0,c==0),程序就不会运行。注意:DFS正在用于此操作 这是我的节目: capacity = (10,6,5) # Maximum capacities of 3 jugs -> x,y,z x = capacity[0] y = capacity[1] z = capa
capacity = (10,6,5)
# Maximum capacities of 3 jugs -> x,y,z
x = capacity[0]
y = capacity[1]
z = capacity[2]
# to mark visited states
memory = {}
# store solution path
ans = []
def get_all_states(state):
# Let the 3 jugs be called a,b,c
a = state[0]
b = state[1]
c = state[2]
if(a==8 and b==0 and c==0):
ans.append(state)
return True
# if current state is already visited earlier
if((a,b,c) in memory):
return False
memory[(a,b,c)] = 1
#empty jug a
if(a>0):
#empty a into b
if(a+b<=y):
if( get_all_states((0,a+b,c)) ):
ans.append(state)
return True
else:
if( get_all_states((a-(y-b), y, c)) ):
ans.append(state)
return True
#empty a into c
if(a+c<=z):
if( get_all_states((0,b,a+c)) ):
ans.append(state)
return True
else:
if( get_all_states((a-(z-c), b, z)) ):
ans.append(state)
return True
#empty jug b
if(b>0):
#empty b into a
if(a+b<=x):
if( get_all_states((a+b, 0, c)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b-(x-a), c)) ):
ans.append(state)
return True
#empty b into c
if(b+c<=z):
if( get_all_states((a, 0, b+c)) ):
ans.append(state)
return True
else:
if( get_all_states((a, b-(z-c), z)) ):
ans.append(state)
return True
#empty jug c
if(c>0):
#empty c into a
if(a+c<=x):
if( get_all_states((a+c, b, 0)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b, c-(x-a))) ):
ans.append(state)
return True
#empty c into b
if(b+c<=y):
if( get_all_states((a, b+c, 0)) ):
ans.append(state)
return True
else:
if( get_all_states((a, y, c-(y-b))) ):
ans.append(state)
return True
return False
initial_state = (10,0,0)
print("Starting work...\n")
get_all_states(initial_state)
ans.reverse()
for i in ans:
print(i)
容量=(10,6,5)
#最大容量为3罐->x、y、z
x=容量[0]
y=容量[1]
z=容量[2]
#标记访问过的国家
内存={}
#存储解决方案路径
ans=[]
def获取所有状态(状态):
#让这三个罐子分别称为a、b、c
a=状态[0]
b=状态[1]
c=状态[2]
如果(a==8,b==0,c==0):
ans.append(状态)
返回真值
#如果先前已访问当前状态
如果((a,b,c)在内存中):
返回错误
存储器[(a,b,c)]=1
#空罐子
如果(a>0):
#把a倒进b
如果(a+B)你从10升开始,从不让任何水流出,那么你永远不会进入少于10升的状态。但是你的最终状态(8,0,0)只有8升。@BoarGules考虑到这个问题有一个标签,我认为这是一个公平的假设。