首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python语言中的HackerRank记号和玩具问题

Python语言中的HackerRank记号和玩具问题
EN

Stack Overflow用户
提问于 2021-02-17 15:27:32
回答 3查看 267关注 0票数 0

我正在尝试解决这个问题:

http://www.hackerrank.com/challenges/mark-and-toys

由于某些原因,我无法使用当前的解决方案获得正确的预期输出。

预期输出:

代码语言:javascript
复制
He can buy items that cost [1, 5, 10, 12] for 28
The maximum is 4 items

当前输出:

代码语言:javascript
复制
He can buy items that cost [1, 5, 10, 12, 111] for 139
The maximum is 5 items

我目前的解决方案是:

代码语言:javascript
复制
prices = [1, 12, 5, 111, 200, 1000, 10]
k = 50

def maximumToys(prices, k):
    sortedPrices = sorted(prices)
    total = 0
    toys = []
    for i in range(len(sortedPrices)):
        if total <= k:
            total += sortedPrices[i]
            toys.append(sortedPrices[i])
        else:
            break
    print(f"He can buy items that cost {toys} for {total}")
    print(f"The maximum is {len(toys)} items")
    
print(maximumToys(prices, k))
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-02-17 15:35:44

您的if语句现在只确定您是否低于总金额,然后添加下一项。然而,你应该检查你是否添加了下一个项目,如果你仍然低于你拥有的总金额。我只更改了if语句:

代码语言:javascript
复制
prices = [1, 12, 5, 111, 200, 1000, 10]
k = 50


def maximumToys(prices, k):
    sortedPrices = sorted(prices)
    total = 0
    toys = []
    for i in range(len(sortedPrices)):
        if total+sortedPrices[i] <= k:
            total += sortedPrices[i]
            toys.append(sortedPrices[i])
        else:
            break
    print(f"He can buy items that cost {toys} for {total}")
    print(f"The maximum is {len(toys)} items")


print(maximumToys(prices, k))

输出:

代码语言:javascript
复制
He can buy items that cost [1, 5, 10, 12] for 28
The maximum is 4 items
票数 1
EN

Stack Overflow用户

发布于 2021-02-17 15:35:51

问题出在这段代码上:

代码语言:javascript
复制
if total <= k:
    total += sortedPrices[i]
    toys.append(sortedPrices[i])

您可以检查

在添加新元素之前添加新元素,而只有在以下情况下才应添加该元素:

不超过

添加新项目后。

因此,正确的代码应该是:

代码语言:javascript
复制
if total + sortedPrices[i] <= k: # add the item only when we don't exceed by adding it
    total += sortedPrices[i]
    toys.append(sortedPrices[i])
票数 1
EN

Stack Overflow用户

发布于 2021-02-17 15:46:01

您的代码中的错误已由

克里希纳·乔拉西亚

..。

另一种方法是减去

来自

并检查是否

仍然大于或等于

然后递增

,否则会中断循环。您不需要在函数中打印完整的字符串消息。只需从你的方法中返回count的值即可。这是在各种编码实践网站上所期望的。

代码语言:javascript
复制
def maximumToys(prices, k):
prices.sort()
count = 0
for price in prices:
    if k-price >= 0:
        count = count + 1
        k -= price
    else:
        break
return count
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66237444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档