Open
Conversation
t0hsumi
reviewed
Jan 10, 2025
| ``` | ||
| characters_to_wordじゃなくてcharacters_to_anagramsの方がわかりやすいか? | ||
|
|
||
| tuple(sorted(string))じゃなくてstr(sorted(string))でもいいのか。 |
There was a problem hiding this comment.
ここでstrを使った気持ちとしては、
- dictはhashableをkeyにとる https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
- immutableなobjectならhashableなはず https://docs.python.org/3/glossary.html#term-hashable
- strはimmutable https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str:~:text=strings%20are%20immutable%20sequences%20of%20unicode%20code%20points.
みたいな流れです。charの出現の組み合わせという意味だとtupleの方が適当ですね。
Owner
Author
There was a problem hiding this comment.
詳しい解説ありがとうございます。参考になります。
oda
reviewed
Jan 10, 2025
| return list(characters_to_word.values()) | ||
| ``` | ||
|
|
||
| sortedは文字列に使った場合、個々が分けられたlistを返す。上のコードは `tuple(sorted(word))` で十分 |
There was a problem hiding this comment.
sorted は iterable をソートしますね。str は iterable ですね。
colorbox
reviewed
Jan 11, 2025
| def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
| character_to_word = {} | ||
| for word in strs: | ||
| characters_tuple = sorted(tuple(word)) |
There was a problem hiding this comment.
tupleに対して_tupleという接尾辞を持った変数名は冗長だと思っています。
tupleであることを強調したいとのであればこれで良いと思います。
sorted_charactersなどのほうがやろうとしていることに対して直截な名前で読みやすいです。
Owner
Author
There was a problem hiding this comment.
確かにsortedかtupleのどちらを入れるかと言われればsortedを変数名に入れた方が良いと感じました。
長いコードだと変数の型を忘れてしまうことがあるので型を名前に含める癖がついてます。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
問題
https://leetcode.com/problems/group-anagrams/description/