我正试着解决这个小问题已经快一个小时了。
Python是一个喜欢水果的麻省理工学院学生。他每天都带着不同种类的水果(用大写字母表示),从他家到麻省理工学院校园在路上吃东西。但他吃水果的方式是独一无二的。每次吃完水果后(除了他刚到校园时吃的最后一个水果),他休息30秒,除了刚吃的水果外,他还买了一种水果。有一天,他的密友Cobra决定继续检查Python。他在去麻省理工学院校园的路上跟着他,记下了他以串形(如AABBBBCA)的形式吃的水果的种类。当Cobra到达校园时,你能帮他确定不同类型的水果中Python的最大数量吗? 编写一个包含两个参数的函数nfruits:
Python (长度< 10)。Python在旅途中吃水果的串形,如Cobra所观察到的。当Python到达校园时,该函数应该从不同类型的水果中返回最大数量。
例如,如果初始值为{'A': 1, 'B': 2, 'C': 3},而字符串模式为AC,那么:
A,更新后的值为{'A': 0, 'B': 2, 'C': 3}。Python购买B和C,更新后的值为{'A': 0, 'B': 3, 'C': 4}{'A': 0, 'B': 3, 'C': 3}现在Python已经到达校园了。因此函数将返回3,这是三个水果数量的最大值。
对于MOOC来说,这是一个可选的练习,因此它没有分级:我解决了更难的问题(更难),但我无法解决它。
我的尝试:
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)]发布于 2016-02-09 17:14:27
如何在任何地方添加1,然后为特定的键减去2呢?
有点像
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:
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)]https://stackoverflow.com/questions/35297782
复制相似问题