python - 编写代码找到铁条的最大切割
问题描述
我目前正在尝试编写一个 Python 程序,该程序可以找到 5m 铁棒的最大切割。允许的切割为:0.5m、1m、1.2m 和 2m。鉴于我必须找到所有匹配或接近 5m 的组合。组合示例:
- 10*0.5 = 5m
- 7*0.5 + 1.2 = 4.7m
第二种组合也很好,因为我们不能产生 0.3m 的切口,所以我们把它扔掉了。一个组合内的顺序很重要,
7x0.5 + 1.2 = 1.2 + 7x0.5
所以我们只需要计算一次。所以理想情况下,我的程序会输入一个文件,并编写一个包含所有组合的文件,例如:
c1 = 10*0.5
c2 = 7*0.5 + 1.2
....
任何人都可以分享从哪里开始的建议吗?谢谢你。
解决方案
也许这就是你要找的?
x = [2, 1.2, 1, 0.5]
max_val = 5
def find_next(state, idx, check=False):
if(idx == len(x)):
return print_it(state, check)
if(sum(state) + x[idx] > max_val):
find_next(state, idx + 1, True)
else:
find_next(state + [x[idx]], idx)
find_next(state, idx + 1)
def print_it(state, check):
if check:
print("")
print(sum(state),state)
return
find_next([],0)
It recursively finds the next value until it runs out of values, and it tracks the current state with a simple list which it prints with print_it
function. I will leave the formatting and file storage up to you, which can easily be implemented in that function.
推荐阅读
- python - 将网络抓取的结果分组到各个部分
- html - CSS 和 HTML 中未设置背景颜色
- javascript - 添加 .indexOn 安全规则与不添加安全规则之间是否存在性能差异?
- typescript - 元素隐式具有“任何”类型,因为类型对象没有索引签名
- r - 如果在 R 中满足条件,则提供空参数
- sql - 选择是否不同计数> 2?
- javascript - 查找最近的 x,y 坐标
- json - 使用字典从 API 解析 Json
- python - ImportError:无法使用 Office 365 项目从“O365”导入名称“帐户”
- node.js - NodeJS botbuilder SDKv4