Skip to content

14. Longest Common Prefix#3

Closed
rm3as wants to merge 6 commits intomainfrom
leetcode_easy
Closed

14. Longest Common Prefix#3
rm3as wants to merge 6 commits intomainfrom
leetcode_easy

Conversation

@rm3as
Copy link
Copy Markdown
Owner

@rm3as rm3as commented Apr 11, 2024

if j == len(strs)-1:
ans = strs[0][0:i]

return ans
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

s = Solution()
s.longestCommonPrefix(["aaaaa", "a", "aaa"])
'aaa'
になりませんか。

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.

すみません、こちら不正解の時の回答でした。先ほど新たにpushしました。

# ["", "a"]
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
ans = ""
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ans と言う変数名は、プログラム中で変数に格納されている値がどのようなものであるかを表していないように思います。別の言い方をすると、 ans または answer は、プログラムの外側の世界で、問題が出題されており、その問題の答えを表すという視点から来ており、プログラムの中の世界の存在ではないと思います。
common_prefix あたりはいかがでしょうか?

min_len = min(len(str) for str in strs)

# 最初の文字列strs[0]のj番目の文字が他の文字列のj番目と一致しなければansを更新せずに終了
for j in range(min_len):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

インデックスを表す変数が j という点に違和感を感じました。短いプログラムであれば、 i を使ったあとに j と書くことはあると思います。 i または index あたりにするのはいかがでしょうか?

def longestCommonPrefix(self, strs: List[str]) -> str:
ans = ""
# strsの中の最小文字数が何文字か調べる
min_len = min(len(str) for str in strs)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

個人的には、変数名の英単語は省略せずに書いたほうが良いと思います。理由は、そのほうが読んでいて、省略形が何の省略形かを考える必要が無くなり、認知負荷が小さくなり、最短で正確にコードを理解することができると思うためです。
ただし、 number_of_minimum_number_of_ といった頻繁に出現するものについては、 num_min_ と省略しても良いと思います。このあたりは、所属するチームの中で合意形成を作った上で省略するのが良いと思います。

for j in range(min_len):
if any(strs[0][j] != str[j] for str in strs):
return ans
else:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

early return の書き方に従い、 else: を消したほうが読みやすくなると思います。

early return とは、本筋に関係ない例外処理等を、できるだけ早い段階で行い、 break・continue・return 等で打ち切り、本筋を下のほうにまとめて書くという書き方です。このような書き方をすることによって、本筋に関係ない処理をワーキングメモリーから追い出し、認知負荷を下げ、最短で正確にコードを理解させることができると思います。

ただし、今回は処理が短いため、 if else で書いても、大きな差はないと思います。

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.

3 participants