파이썬은 타입 지정언어가 아니기 때문에 객체의 동작이 객체의 실질적인 덕 타입핑에 의존한다.
votes = {
'otter':1281,
'polar bear':587,
'fox':863,
}
def poplulate_ranks(votes, ranks):
names = list(votes.key())
names.sort(key=votes.get, reverse=True)
for i , name in enumerate(names,1):
ranks[name]=i
def get_winner(ranks):
return next(iter(ranks))
ranks = {}
populate_ranks(votes, ranks)
print(ranks)
winner= get_winner(ranks)
print(winner)
#{'otter':1, 'fox':2, 'polar bear':3}
otter
변경 시 UI 요소에서 결과를 보여줄 때는 등수가 아닌 알파벳 순서로 표시해야한다.
from collections.abc import MutableMapping
class SortedDict(MutableMapping):
def __init__(self):
self.data = {}
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key,value):
self.data[key] =value
def __delitem__(self, key):
del self.data[key]
def __iter__(self):
keys= list(self.data.keys())
keys.sort()
for key in keys:
yield key
def __len__(self):
return len(self.data)
sorted_ranks = SortedDict()
populate_ranks(votes, sorted_ranks)
print(sorted_ranks.data)
winner = get_winner(sorted_ranks)
print(winner)
#{'otter':1, 'fox':2, 'polar bear':3}
fox
해결방법
def get_winner(ranks):
for name, rank in ranks.items():
if rank ==1:
return name
winner = get_winner(sorted_ranks)
print(winner)
#otter
두번쩨
def get_winner(ranks):
if not isinstance(ranks, dict):
raise TypeError('dict 인스턴스가 필요합니다')
return next(iter(ranks))
get_winner(sorted_ranks)
세 번째
#타입 애너테이션을 붙여서 mypy도구를 엄격한 모드로 사용
from typing import DIct, MutableMapping
def populate_ranks(votes: Dict[str, int],
ranks: Dict[str, int])->None:
name = list(votes.keys())
names.sort(key=votes.get, reverse=True)
for i,name in enumerate(names,1):
rank[name] =i
def get_winner(ranks:Dict[str, int]) -> str:
return next(iter(ranks))
class SortedDict(MutableMapping[str,int]):
...
votes = {
'otter':1281,
'polar bear':587,
'fox':863,
}
sorted_ranks = SortedDict()
populate_ranks(votes, sorted_ranks)
print(sorted_ranks.data)
winner = get_winner(sorted_ranks)
print(winner)