凑单算法

2019-08-13 14:41:43 +08:00
 JCZ2MkKb5S8ZX9pq

刚好买东西想到这么个问题,各位有啥思路嘛?

3001 次点击
所在节点    算法
3 条回复
imzhoukunqiang
2019-08-13 16:31:23 +08:00
看起来是 [背包问题] 吧
geelaw
2019-08-13 16:38:09 +08:00
这是一个背包问题,一般化后的决定版本是 NP 困难的。
JCZ2MkKb5S8ZX9pq
2019-08-13 16:44:10 +08:00
@imzhoukunqiang
@geelaw
不懂啥是背包问题,凑合写了一个,基本满足我自己的需求了。
缩进随缘吧。有空改个 js 的挂网页。

item = {'creatine': 64.35, 'protein': 103.35, 'bcaa': 64.35}
priceLimit = 428

# 格式化商品数据
itemDict = {}
for name, price in item.items():
itemDict.setdefault(price, '')
itemDict[price] += f'/{name}'
itemDict[price] = itemDict[price].lstrip('/')
itemList = sorted(itemDict.items(), key=lambda x: x[1])
drawTitle('ITEMLIST')
[print(f'{price:8.2f} | {name}') for price, name in itemList]
print(f'\nTraget Price: {priceLimit:.2f}')
r = {}


def orderNum(itemList, prevOrder='', prevPrice=0):
for num in range(999):
price, name = itemList[0]
thisOrder = f'{prevOrder} + {num} {name}' if num else ''
thisPrice = prevPrice + price * num

# 如果当前价格超了 就不再增加数量
if thisPrice >= priceLimit:
r[thisOrder.strip('+ ')] = thisPrice
return

# 如果价格没超 就往下一位
if len(itemList) > 1:
orderNum(itemList[1:], thisOrder, thisPrice)


orderNum(itemList)
# 按总价升序
r = sorted(r.items(), key=lambda d: d[1])
drawTitle('RESULT')
[print(f'{total:>8.2f} | {order}') for order, total in r]

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/591500

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX