0%

[學習] Check.io - Bigger Price

check.io 上的題目:求出 list 裡 topN 貴的物品儲存方式是dicionary,每個物品各有兩個 key 分別為 name & price
此系列文章主要是自己在解題時覺得有趣的題目,記錄下來讓自己以後好複習,有興趣的人可以參考看看

先來看看題目

看完題目可能會覺得小複雜,一般題目出有關 dictionary 的題目大多都只要找出一個最大或最小的 key 值,很直覺就會想到要用max/min的函式來解決(詳細用法在此篇文章有提到),這裡還要找不只一個,但認真想想其實也沒很難,用sort就可以一行輕鬆解決了。

sorted 的用法

語法:sorted(list, key=parameters, reverse=True/False)

基本

1
2
3
x = [3, 2, 6, 1, 9]
y = sorted(x)
print(y)

output:

1
[1, 2, 3, 6, 9]

反向排序(大到小)

1
y = sorted(x, reverse=True)

output:

1
[9, 6, 3, 2, 1]

進階

example 1:

1
2
3
4
x = [("Amy", 150, 60),
("Emily", 154, 55),
("Wen", 145, 70)]
print(sorted(x, key=lambda a: a[1]))

output:

1
[('Wen', 145, 70), ('Amy', 150, 60), ('Emily', 154, 55)]

example 2:

1
2
3
4
x = [{"fruit": "apple", "price": 20},
{"fruit": "banana", "price": 18},
{"fruit": "peach", "price": 25}]
print(sorted(x, key=lambda x: x["price"]))

output:

1
[{'fruit': 'banana', 'price': 18}, {'fruit': 'apple', 'price': 20}, {'fruit': 'peach', 'price': 25}]

解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def bigger_price(limit: int, data: list) -> list:
"""
TOP most expensive goods
"""
return sorted(data, key=lambda d: d['price'], reverse=True)[:limit]


if __name__ == '__main__':
from pprint import pprint
print('Example:')
pprint(bigger_price(2, [
{"name": "bread", "price": 100},
{"name": "wine", "price": 138},
{"name": "meat", "price": 15},
{"name": "water", "price": 1}
]))

# These "asserts" using for self-checking and not for auto-testing
assert bigger_price(2, [
{"name": "bread", "price": 100},
{"name": "wine", "price": 138},
{"name": "meat", "price": 15},
{"name": "water", "price": 1}
]) == [
{"name": "wine", "price": 138},
{"name": "bread", "price": 100}
], "First"

assert bigger_price(1, [
{"name": "pen", "price": 5},
{"name": "whiteboard", "price": 170}
]) == [{"name": "whiteboard", "price": 170}], "Second"

print('Done! Looks like it is fine. Go and check it')