版权声明:欢迎联系我转载!欢迎交流分享!转载和分享请注明出处! https://blog.csdn.net/u014303046/article/details/82555498
Best stock
一、题目描述
要求:给定货物价格,找到价格最高的货物
输入:一个 货物:价格
的字典
输出:价格最高的货物
示例:
best_stock({
'CAC': 10.0,
'ATX': 390.2,
'WIG': 1.2
}) == 'ATX'
best_stock({
'CAC': 91.1,
'ATX': 1.01,
'TASI': 120.9
}) == 'TASI'
二、 解题示例
1. 遍历字典
def best_stock(data):
# your code here
tmp = 0
good = ''
for item in data:
if data[item] > tmp:
good = item
tmp = data[item]
return good
if __name__ == '__main__':
print("Example:")
print(best_stock({
'CAC': 10.0,
'ATX': 390.2,
'WIG': 1.2
}))
# These "asserts" are used for self-checking and not for an auto-testing
assert best_stock({
'CAC': 10.0,
'ATX': 390.2,
'WIG': 1.2
}) == 'ATX', "First"
assert best_stock({
'CAC': 91.1,
'ATX': 1.01,
'TASI': 120.9
}) == 'TASI', "Second"
2. max()
def best_stock(data):
return max(data, key=data.__getitem__)
if __name__ == '__main__':
print("Example:")
print(best_stock({
'CAC': 10.0,
'ATX': 390.2,
'WIG': 1.2
}))
# These "asserts" are used for self-checking and not for an auto-testing
assert best_stock({
'CAC': 10.0,
'ATX': 390.2,
'WIG': 1.2
}) == 'ATX', "First"
assert best_stock({
'CAC': 91.1,
'ATX': 1.01,
'TASI': 120.9
}) == 'TASI', "Second"
或者
def best_stock(data):
return max(data, key=lambda x: data[x])