リンク先の問題を見る限り...
Output Format
Print the three most common characters along with their occurrence count each on a separate line.
Sort output in descending order of occurrence count.
If the occurrence count is the same, sort the characters in ascending order.
ここでのascendingとは、アルファベット順のことではないでしょうか?
そう解釈してよいのなら、辞書に要素を追加した順を意識する必要はないはずです。
Counter.most_commonで出現回数順に並び変え、その後にアルファベット順にソートすればよいかと。
Python
1from collections import Counter
2
3counter = Counter(input())
4
5for k, v in sorted(counter.most_common(), key=lambda x: x[0])[:3]:
6 print(k, v)
動作テストはしていないので、何かバグがあるかもしれませんが。
追記:バグ、ありました。ちょっと修正します。
修正しました。結局Counter.most_commonは使ってないです。
Python
1from collections import Counter
2
3counter = Counter(input())
4for k, v in sorted(counter.items(), key=lambda x: (-x[1], x[0]))[:3]:
5 print(k, v)
さらに改造しました。こっちの方がわかりやすい気もしますね。
Python
1from collections import Counter
2from operator import itemgetter
3
4counter_list = list(Counter(input()).items())
5counter_list.sort(key=itemgetter(0))
6counter_list.sort(key=itemgetter(1), reverse=True)
7
8for k, v in counter_list[:3]:
9 print(k, v)
順番が安定しない理由
Counterは要素の挿入順序を記憶しないからです。
引用元:Python標準ライブラリ - 8.3.2. Counter オブジェクト
class collections.Counter([iterable-or-mapping])
Counter はハッシュ可能なオブジェクトをカウントする dict のサブクラスです。これは、要素を辞書のキーとして保存し、そのカウントを辞書の値として保存する、順序付けされていないコレクションです。
一方、OrderedDictは要素の挿入順序を記憶します。
引用元:Python標準ライブラリ- 8.3.6. OrderedDict オブジェクト
class collections.OrderedDict([items])
通常の dict メソッドをサポートする、辞書のサブクラスのインスタンスを返します。 OrderedDict は、キーが最初に追加された順序を記憶します。新しい項目が既存の項目を上書きしても、元の挿入位置は変わらないままです。
このように、これらの用途は異なります。
なお、OrderedCounterたるクラスが実装例として紹介されています。
順序付き辞書と Counter クラスを組み合わせると、要素が最初に現れた順を記憶するカウンタができます:
class OrderedCounter(Counter, OrderedDict):
'Counter that remembers the order elements are first encountered'
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
def __reduce__(self):
return self.__class__, (OrderedDict(self),)
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/11/01 07:47
2017/11/01 07:49
退会済みユーザー
2017/11/01 07:53