Skip to content

Conversation

@nittoco
Copy link
Owner

@nittoco nittoco commented Apr 25, 2025

https://leetcode.com/problems/top-k-frequent-elements/description/

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

- デフォルトの実装。eqはisを呼ぶ。等しくない場合はNot Implemented。__ne__はその逆。
- そのほかの比較演算子は、デフォルト挙動は存在しない。<または==であることは≤を保証しない。比較演算子がない場合、<や≤はTypeErrorとなる。
- reflectionというのがよくわからなかったが、chatGPTに聞いた感じ、`a < b` で `a.__lt__(b)` がダメだったら `b.__gt__(a)` を試す。ということらしい?
- こういう用語、常識なのか?
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

いや、この reflection は私は知らないですね。文脈から推測できますが数学用語でもないと思います。

通常 reflection というと、文字列からオブジェクトやアトリビュートなどを呼び出す仕組みを指します。
https://docs.python.org/3/c-api/reflection.html

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

数学用語で反射律を満たす関係がreflexive relationですが、a<b <=> b>aによって<>がreflectionであるというのは私は聞いたことないかもしれません。少なくともエンジニアの用語ではないと思います。
https://en.wikipedia.org/wiki/Reflexive_relation

高校等でも習う命題の「逆」、converseというのが<>の関係性を表す正しい用語と思います。
https://en.wikipedia.org/wiki/Converse_relation

```

- Counter、most_commonでの実装。実務ならこれでOK
- CPythonのmost_commonの[実装](https://github.com/python/cpython/blob/17718b0503e5d1c987253641893cab98e01f4535/Lib/collections/__init__.py#L625)を見てみると、nがNoneの時以外に、いちいちheapqをimportしてnlargest()使っているのが不思議。単純にsortedの方がオーバーヘッドなさそうなので。

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

k << nの状況を想定していると思います。
https://github.com/python/cpython/blob/659cb7e6b8e83e1541fc27fd29d4846e940b600e/Lib/heapq.py#L397
に記載がありますが、
n=10,000,000に対して、100largestの場合は比較が10,009,401回ぐらいになり、n log(n)よりもだいぶ少なくなります。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

なるほど、ありがとうございます。コメントに書いてありましたね。

num_to_frequency = defaultdict(int)
for num in nums:
num_to_frequency[num] += 1
return sorted(num_to_frequency, key=num_to_frequency.get, reverse=True)[:k]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ただのコメントなのですが、辞書をsortedするとリストになって返ってくるのですね、パット見でえ?となりましたが調べてわかりました。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

意識せずにやってしまっておりました。ありがとうございます

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants