Conversation
| class Solution: | ||
| def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
| def count_char_frequency(string: str) -> Tuple[int, ...]: | ||
| char_frequency = [0] * 26 |
There was a problem hiding this comment.
alphabet_count = 26
char_frequency = [0] * alphabet_countとしてマジックナンバーを避けると良いと思いました
| frequency = Counter(s) | ||
| lowercase_frequency = tuple( | ||
| frequency[lowercase] for lowercase in string.ascii_lowercase | ||
| ) |
There was a problem hiding this comment.
あー、上は誤りですね。ジェネレータ式は文法上内包表記とは別物でした。
https://docs.python.org/3/reference/expressions.html#generator-expressions
https://peps.python.org/pep-0289/
| def count_char_frequency(string: str) -> Tuple[int, ...]: | ||
| char_frequency = [0] * 26 | ||
| for char in string: | ||
| index = ord(char) - ord('a') |
There was a problem hiding this comment.
https://docs.python.org/3/library/functions.html#ord
文字コードを一回確認しておいてください。
たとえば、C++ だと、ASCII とは限らないのでアルファベットが連続しているとは限りません。
https://discord.com/channels/1084280443945353267/1301587996298182696/1309561565187538964
(コードの正誤ではなく)確認したい気持ちがあるかどうかを大事にしてください。
There was a problem hiding this comment.
asciiでa-zが連続していることは知っていましたが、連続していない文字コードがあることは一切想定していなかったです。
There was a problem hiding this comment.
Python ord は Unicode のコードポイントが返ってくるので連続しているとしていいんです。つまり、結果的には同じコードになるんですが、しかし「Python ord は Unicode のコードポイントだからアルファベット部分は ASCII と同じ、だから連続しているとしてよい」と思って書いたほうがいいでしょう。
C / C++ だと、この保証はないのですが、しかし、そういう文字コードは稀なので「意図的にサポートを切り捨てた」と思っていればいいです。
|
|
||
| - https://github.com/katataku/leetcode/pull/11/files | ||
| - `list(dict.values())`としていた | ||
| - `sorted_string = ''.join(sorted(string))`としていた。これくらいなら、`sorted(string)`を別変数でおかなくても十分読めるなと感じた |
There was a problem hiding this comment.
一応、str(sorted(string)) が ''.join(sorted(string)) とは異なるものであるという認識があるかの確認はしておきます。
There was a problem hiding this comment.
違いについて説明せよと言われてもできなそうなので、調べました。
文字列をsortしたリストを引数にした場合、どちらも返す値は変わらないので今回はどっちでもいいのかなぁくらいの感想でした。
sorted(string)
- https://docs.python.org/3/library/functions.html#sorted
- iterableを受け取りlistを返す
- iterable
str(sorted(string))
- https://docs.python.org/3/library/stdtypes.html#str
str(object)は内部でtype(object).str(object)`を呼ぶ- The default implementation defined by the built-in type object calls object.repr().
- https://github.com/python/cpython/blob/main/Objects/typeobject.c#L9908-L9925
''.join(sorted(string))
https://leetcode.com/problems/group-anagrams/description/