求使E=4N+0.3n最小的筹码组合的正确Python代码实现
筹码组合最优解问题
给定面额数组 denominations = [0.1, 0.5, 1, 5, 20, 100, 500],需为指定金额A找到最优筹码组合,使得目标函数 E = 4N + 0.3n 的值最小。其中:
N:使用的不同类型筹码的总数n:所有筹码的总个数
示例:当金额A=6.8时,符合要求的组合为 [8, 0, 6, 0, 0, 0, 0](对应0.1元筹码8个、1元筹码6个),对应的E = 4*2 + 0.3*14 = 12.2(N=2,n=8+6=14)。
我尝试编写的代码无法得到正确结果,请求协助编写正确代码,尝试代码如下:
from itertools import permutations from itertools import combinations import math def elem_index(elem, arr): try: index = arr.index(elem) except ValueError: index = -1 return index def comb(arr, pos): comb_temp = combinations(arr, pos) result = [list(p) for p in comb_temp] return result def chip_denomination(amt_low, denominations): #denominations = [x for x in original_denominations if x <= amt_low] E = 1000 temp_low = amt_low final = [0 for i in range(len(denominations))] length = len(denominations) N = 1 while (N < length): comb_arr = comb(denominations, N) chip_count_low = [0 for i in range(N)] for denom_new in comb_arr: denom_new.sort(reverse=True) i = 0 while (i < N): chip_count_low[i] = math.floor(temp_low/denom_new[i]) temp_low = temp_low%denom_new[i] if (chip_count_low[i] == 0 or (i == N-1 and temp_low > 0)): i = N else: i = i + 1 if (elem_index(0, chip_count_low) == -1): E_new = 4*N + 0.3*sum(chip_count_low) if (E_new < E): E = E_new for j in range(N): final[elem_index(denom_new[j], denominations)] = chip_count_low[j] if (E - 4*(N+1) < 0): N = length else: print(f"Chips = {final} and Effort = {E} and N={N}") N = N + 1 denominations = [0.1, 0.5, 1, 5, 20, 100, 500] amt_low = 6.8 chip_denomination(amt_low, denominations)
内容的提问来源于stack exchange,提问作者Vineet Mangal
相关产品推荐
相关产品推荐

