-
Notifications
You must be signed in to change notification settings - Fork 0
Group Anagrams step1-3 #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
いいと思います
``` | ||
characters_to_wordじゃなくてcharacters_to_anagramsの方がわかりやすいか? | ||
|
||
tuple(sorted(string))じゃなくてstr(sorted(string))でもいいのか。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ここで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の方が適当ですね。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
詳しい解説ありがとうございます。参考になります。
return list(characters_to_word.values()) | ||
``` | ||
|
||
sortedは文字列に使った場合、個々が分けられたlistを返す。上のコードは `tuple(sorted(word))` で十分 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sorted は iterable をソートしますね。str は iterable ですね。
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
tupleに対して_tuple
という接尾辞を持った変数名は冗長だと思っています。
tupleであることを強調したいとのであればこれで良いと思います。
sorted_characters
などのほうがやろうとしていることに対して直截な名前で読みやすいです。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
確かにsortedかtupleのどちらを入れるかと言われればsortedを変数名に入れた方が良いと感じました。
長いコードだと変数の型を忘れてしまうことがあるので型を名前に含める癖がついてます。
問題
https://leetcode.com/problems/group-anagrams/description/