Skip to content

Update 347.Top K Frequent Elements.md - #9

Open
wanwan87 wants to merge 2 commits into
wanwan87-347.Top-K-Frequent-Elementsfrom
wanwan87-347.Top-K-Frequent-Elements-1
Open

Update 347.Top K Frequent Elements.md#9
wanwan87 wants to merge 2 commits into
wanwan87-347.Top-K-Frequent-Elementsfrom
wanwan87-347.Top-K-Frequent-Elements-1

Conversation

@wanwan87

Copy link
Copy Markdown
Owner

```python
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
element_counter = {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この用途であれば、 defaultdict や Counter のほうがシンプルに書けると思います。
https://docs.python.org/ja/3.14/library/collections.html#collections.defaultdict
https://docs.python.org/ja/3.14/library/collections.html#collections.Counter

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

defaultdict知りませんでした、ありがとうございます。
存在しないキーを読んだときにデフォルト値を生成してくれるんですね。

element_counter[num] = element_counter + 1
でokになる。

heapq.heappop(heap)

res = []
print(heap)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

デバッグ出力は削除してからレビューに回したほうが良いと思います。そのほうが、レビューワーにとってノイズとならないと思います。

```python
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
element_counter = {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

dict 型の変数名はキーと値にどのような値が含まれるかを表すようにすると、読み手にとって理解しやすくなると思います。今回の場合は num_to_frequency あたりになると思います。ただ、 element_counter でも acceptable だと思います。

for num in nums:
element_counter[num] = 1 + element_counter.get(num, 0)

heap = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

こちらのコメントをご参照ください。
rimokem/arai60#25 (comment)

今回の場合は frequencies_and_nums はいかがでしょうか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます

個人的にはどのような値が格納されているかに着目したいです

このあたりを意識してみます

def topKFrequent(self, nums: List[int], k: int) -> List[int]:
element_counter = {}
for num in nums:
element_counter[num] = 1 + element_counter.get(num, 0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

自分なら element_counter.get(num, 0) + 1 と書くと思います。理由は b + a * x より a * x + b と書くほうが自然に感じるためです。趣味の範囲だと思います。

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.

2 participants