首页 > 解决方案 > 编写代码找到铁条的最大切割

问题描述

我目前正在尝试编写一个 Python 程序,该程序可以找到 5m 铁棒的最大切割。允许的切割为:0.5m、1m、1.2m 和 2m。鉴于我必须找到所有匹配或接近 5m 的组合。组合示例:

第二种组合也很好,因为我们不能产生 0.3m 的切口,所以我们把它扔掉了。一个组合内的顺序很重要,

7x0.5 + 1.2 = 1.2 + 7x0.5

所以我们只需要计算一次。所以理想情况下,我的程序会输入一个文件,并编写一个包含所有组合的文件,例如:

c1 = 10*0.5 
c2 = 7*0.5 + 1.2 
....

任何人都可以分享从哪里开始的建议吗?谢谢你。

标签: pythonpython-3.xmathematical-optimization

解决方案


也许这就是你要找的?

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.


推荐阅读