【每日一题20220817】干杯,啤酒金字塔

:mage: 有一天你贡献了一个非常好的idea,老板给了你一笔奖金。为了庆祝,你把你的朋友们带到可怕的潜水酒吧,并使用奖金购买和建造最大的三维啤酒罐金字塔。然后与朋友们进入狂欢。

啤酒罐金字塔建造的规则是:顶层1罐,第二层4罐,下一层9罐,下一层16罐,25罐…

完成 beeramid 函数以返回您可以制作的啤酒罐完整金字塔的层数,给定以下参数:

您的奖金 bonus,以及啤酒的价格 price

例如:

beeramid(1500, 2)  # should === 12
beeramid(5000, 3) # should === 16

题目难度:中等
题目来源:Beeramid | Codewars


def beeramid(bonus: float, price: float) -> int:
    # your code here

assert beeramid(9, 2) == 1
assert beeramid(10, 2) == 2
assert beeramid(11, 2) == 2
assert beeramid(21, 1.5) == 3
assert beeramid(454, 5) == 5
assert beeramid(455, 5) == 6
assert beeramid(4, 4) == 1
assert beeramid(3, 4) == 0
assert beeramid(0, 4) == 0
assert beeramid(-1, 4) == 0
assert beeramid(10500, 2) == 24

def beeramid(bonus: float, price: float) -> int:
    num = int(bonus / price)
    count = -1
    index = 1
    while (num >= 0):
        count += 1
        num -= index ** 2
        index += 1
    print(count)
    return count
1 Like
def beeramid(bonus, price):
    layers,sum = 0,0
    while sum <= bonus:
        layers += 1
        sum += (layers**2) * price
    return max(layers-1,0)
1 Like

手机…

解题思路:
1、根据啤酒摆金字塔罐数的规律,每层的数量,
得出来的数字规律是:
总罐数=11+22+3*+44+…+nn
n 就是啤酒能摆出来的层数
2、循环 ii i=1 i++ 汇总叠加ii的值(可摆的总罐数)
总罐数是否小于 用户输入的罐数
得出最后能摆出的层数

def beeramid(bonus: float, price: float) -> int:
    # your code here
    sum=0
    total=int(bonus/price)
    list=[]
    if total==1:
        return 1
    for i in range(1,total):
        sum += i ** 2
        if sum<=total:
            list.append(i**2)
    return len(list)
def beeramid(bonus: float, price: float):
    s = int(bonus / price)
    i = 1
    floor=0
    count = 0
    while s > 0:
        count = count + i * i
        if s >= count:
            i = i + 1
            floor = floor + 1
            continue
        else:
            break
    print(floor)
    return int(floor)
def beeramid(bonus: float, price: float) -> int:
    if bonus <= 0 or price <= 0:
        return 0
    num = bonus // price
    beer_sum = 0
    for i in range(0, int(num) + 1):
        beer_sum += i ** 2
        if beer_sum > num:
            i -= 1
            break
    return i


assert beeramid(9, 2) == 1
assert beeramid(10, 2) == 2
assert beeramid(11, 2) == 2
assert beeramid(21, 1.5) == 3
assert beeramid(454, 5) == 5
assert beeramid(455, 5) == 6
assert beeramid(4, 4) == 1
assert beeramid(3, 4) == 0
assert beeramid(0, 4) == 0
assert beeramid(-1, 4) == 0
assert beeramid(10500, 2) == 24
def beeramid(bonus: float, price: float) -> int:
    layer = 0
    cost = 0

    if bonus <=0 or price <= 0:
        return 0

    while cost <= bonus:
        layer += 1
        cost = cost + layer**2*price
    return layer - 1
关闭