游戏水桶倒水问题Python语言的解决方法,倒水python,Python编程语言关于
游戏水桶倒水问题Python语言的解决方法,倒水python,Python编程语言关于
Python编程语言关于游戏水桶倒水问题的解决方法是怎么样的?问题是:有三个水桶,分别是10升、7升和3升。10升的水桶是满的,要求想办法把另外两个桶变成5升的,并且不能浪费水哦!需要用Python来完成这个游戏,大家有什么好的思路吗?
其他Python相关游戏源码文章推荐:Python实现自动扫雷游戏的方法源码
下边先来看看我的水桶倒水问题Python语言的解决方法:
#! /usr/bin/env python# -*- coding: utf-8 -*-LIMITS = (10, 7, 3)INIT = (10, 0, 0)WIN = (5, 5, 0)from copy import copyclass State: def __init__(self, init_value): self.parent = -1 self.value = init_value self.move = (0, 0, 0) #(from, to, amount) #spawn by put water around def spawn(self): for i in range(len(LIMITS)): #for each cup if not self.value[i]: continue #if empty cup then next for k in range(len(LIMITS)): #otherwise try put water to other cups if i == k: continue val_i = self.value[i] val_k = self.value[k] #1. move all in i to k #2. move i to make k full #so the minimum of the 2 actions is the target min_ik = min(val_i, LIMITS[k] - val_k) new_value = list(copy(self.value)) new_value[i] -= min_ik new_value[k] += min_ik new_value = tuple(new_value) if new_value in g_state_map: #already exists? continue new_state = State(new_value) new_state.parent = g_index new_state.move = (i, k, min_ik) g_states.append(new_state) g_state_map[new_value] = True if new_value == WIN: return True return False#www.iplaypy.comdef print_solution(state): states = [] while state.parent != -1: states.append(state) state = g_states[state.parent] states.reverse() print "At least:", len(states), "steps:" print "(Cup0, Cup1, Cup2) (from, to, amount)" print INIT for state in states: print state.value, state.move#solve the problem here!g_states = [State(INIT)] #initially we have (10, 0, 0)g_state_map = {} #sate:true/false, avoid duplicate statesg_index = 0while g_index < len(g_states): state = g_states[g_index] if state.spawn(): print_solution(g_states[-1]) break g_index += 1result = """At least: 9 steps:(Cup0, Cup1, Cup2) (from, to, amount)(10, 0, 0)(3, 7, 0) (0, 1, 7)(3, 4, 3) (1, 2, 3)(6, 4, 0) (2, 0, 3)(6, 1, 3) (1, 2, 3)(9, 1, 0) (2, 0, 3)(9, 0, 1) (1, 2, 1)(2, 7, 1) (0, 1, 7)(2, 5, 3) (1, 2, 2)(5, 5, 0) (2, 0, 3)"""
python代码中的python reverse方法是列表反转排序,具体使用方法可点击链接查看。
编橙之家文章,
相关内容
- Python算法--最长公共子串算法代码讲解,python算法,Pyt
- 如何用Python os.path.walk方法遍历搜索文件内容的操作详解
- Python脚本随机生成中文验证码源码实例分析,python实例
- Python标准库模块之Sys使用详解,python使用详解,本文主要
- 本地服务更新Python代码 如要使用请适当的修改,pytho
- python抽奖 系统算法代码的简单实现,python抽奖算法代码
- 如何用Python代码实现自动比较两个文件中的代码变化?
- python logging 日志模块使用方法学习,pythonlogging,本文为
- Python近期使用较少算法实现方法,python近期较少算法
- 用Python来处理中文分句的方法_【源码精华】,,我在用
评论关闭