在Python中购买X获取X免费公式

问题描述 投票:-1回答:1

在买一送一的情况下,计算简单,只需将2除以我们想要的数量(例如:免费买3送3,所以得到6)。

但是当它变得更复杂时,比如买4送1免费,如果我们想购买13,那么最好的购买选择(答案是购买11因为你免费获得2)?我发现有趣的是它很容易计算,但是把它放在代码中,我迷失了。

在买4送1,这是我发现的模式,但同样,我不知道如何实际把它放在代码中。

基本上,我想制定“买X得X免费”,所以当给定情况时,它会输出最佳购买选项。例如,如果我想购买其中的13个,则输出“11”。

the quantity we need:    we only need to buy:    what we end up having:

          1                        1                       1
          2                        2                       2
          3                        3                       3
          4                        4                       5
          5                        4                       5
          6                        5                       6
          7                        6                       7
          8                        7                       8
          9                        8                       10
         10                        8                       10
         11                        9                       11
         12                       10                       12
         13                       11                       13
         14                       12                       15
         15                       12                       15
          .                        .                        .
          .                        .                        .
          .                        .                        .
python python-3.x shopping-cart price promotions
1个回答
3
投票

这非常简单:您想要找到需要多少个完整包,以及需要多少个非包装物品。积分部门很方便。

def buy_to_acquire(desired, buy=1, free=0):
    pack = buy + free
    buy_packs = desired // pack
    buy_individual = desired % pack
    return buy * buy_packs + buy_individual

buy_to_acquire(13, buy=4, free=1)
# => 11

替代版本不是那么容易理解,但它对计算机来说要快一点:

import math
def buy_to_acquire(desired, buy=1, free=0):
    return math.ceil(desired * buy / (buy + free))
© www.soinside.com 2019 - 2024. All rights reserved.