首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >除了一个键外,更改字典中的值

除了一个键外,更改字典中的值
EN

Stack Overflow用户
提问于 2016-02-09 16:59:32
回答 1查看 643关注 0票数 0

我正试着解决这个小问题已经快一个小时了。

Python是一个喜欢水果的麻省理工学院学生。他每天都带着不同种类的水果(用大写字母表示),从他家到麻省理工学院校园在路上吃东西。但他吃水果的方式是独一无二的。每次吃完水果后(除了他刚到校园时吃的最后一个水果),他休息30秒,除了刚吃的水果外,他还买了一种水果。有一天,他的密友Cobra决定继续检查Python。他在去麻省理工学院校园的路上跟着他,记下了他以串形(如AABBBBCA)的形式吃的水果的种类。当Cobra到达校园时,你能帮他确定不同类型的水果中Python的最大数量吗? 编写一个包含两个参数的函数nfruits

  • 一本包含水果类型及其数量的非空字典,最初在他离家时用Python (长度< 10)。
  • Python在旅途中吃水果的串形,如Cobra所观察到的。

Python到达校园时,该函数应该从不同类型的水果中返回最大数量。

例如,如果初始值为{'A': 1, 'B': 2, 'C': 3},而字符串模式为AC,那么:

  1. 使用A,更新后的值为{'A': 0, 'B': 2, 'C': 3}
  2. Python购买BC,更新后的值为{'A': 0, 'B': 3, 'C': 4}
  3. C被消耗,更新后的值为{'A': 0, 'B': 3, 'C': 3}

现在Python已经到达校园了。因此函数将返回3,这是三个水果数量的最大值。

对于MOOC来说,这是一个可选的练习,因此它没有分级:我解决了更难的问题(更难),但我无法解决它。

我的尝试:

代码语言:javascript
复制
def nfruits(dictionary, string):
    i = 0
    string = sorted(string)

    for char in string:
        dictionary[char] -= 1
        # print dictionary
        i += 1
        for char in string[i:]:
            dictionary[char] += 1
            # print dictionary

     return dictionary[max(dictionary, key = dictionary.get)]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-09 17:14:27

如何在任何地方添加1,然后为特定的键减去2呢?

有点像

代码语言:javascript
复制
def nfruits(dictionary, string):
    i = 0
    string = sorted(string)

    for idx, char in enumerate(string):
        # We should update other fruits on all steps except the
        # last one
        if idx < len(string) - 1:
            for key in dictionary:
                dictionary[key] += 1
            dictionary[char] -= 2
        else:
            # for the last step - only decrement the fruit
            # Python ate
            dictionary[char] -= 1
        print dictionary
    return dictionary[max(dictionary, key = dictionary.get)]

if __name__ == "__main__":
    dd = {'A': 1, 'B': 2, 'C': 3}
    print nfruits(dd, 'AC')

更新:另一个选项是,当我们浏览dict时跳过char

代码语言:javascript
复制
def nfruits2(dictionary, string):
    i = 0
    string = sorted(string)

    for idx, char in enumerate(string):
        # Update the fruit Python ate
        dictionary[char] -= 1
        # update others he bought, skip this on the last step
        if idx < len(string) - 1:
            for key in dictionary:
                if key != char:
                    dictionary[key] += 1
        print dictionary
    return dictionary[max(dictionary, key = dictionary.get)]
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35297782

复制
相关文章

相似问题

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