穷举法 解决用3个水桶等分8升水 python实现

最近在王晓华老师算法课程中学习到用穷举法解决三个水桶等分8升水。
还是用python来实现一下加深了解

其中用到递归思想,每次向函数中传入当前各桶中水量,以及从第几个倒水状态开始遍历

import pandas as pd

fixed=[[0,1],[0,2],[1,0],[1,2],[2,0],[2,1]] # 固定6种倒水方式

state=pd.DataFrame(columns=["buc0","buc1","buc2"])  # 8 3 5
state = state.append({'buc0': 8,'buc1':0,'buc2':0}, ignore_index=True)

volumn=[8,3,5] # 桶的容量
state_col=state.columns
num=0
def take_action(state,num): 
   current=state.loc[len(state)-1][state_col]
   if current[state_col[0]]==4 and current[state_col[2]]==4:
       return state
   else:
       for id in range(num,6):
           if current[state_col[fixed[id][0]]]>0 and current[state_col[fixed[id][1]]]<volumn[fixed[id][1]]:
               if (volumn[fixed[id][1]]-current[state_col[fixed[id][1]]])>current[state_col[fixed[id][0]]]:
                   current[state_col[fixed[id][1]]]=current[state_col[fixed[id][1]]]+current[state_col[fixed[id][0]]]
                   current[state_col[fixed[id][0]]]=0
                   state=state.append(current,ignore_index=True)
               else: 
                   current[state_col[fixed[id][0]]]=current[state_col[fixed[id][0]]]-(volumn[fixed[id][1]]-current[state_col[fixed[id][1]]])
                   current[state_col[fixed[id][1]]]=volumn[fixed[id][1]]
                   state=state.append(current,ignore_index=True)
                
               if len(state)==len(state.drop_duplicates()):
                   state=take_action(state,0)
                   return state
               else: 
                   state=take_action(state.drop_duplicates(),id+1)  # 当前得到的状态废除 原状态从子状态0开始遍历
                   return state
             
                       

output=take_action(state,0)  

输出结果为:
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值