Conversation
| return False, index + 1 | ||
| return True, index | ||
|
|
||
| def _read_integer(self, s, index: int) -> int: |
There was a problem hiding this comment.
私ならメソッド名は _convert_to_integer にします。
| break # non digit exists | ||
| return result | ||
|
|
||
| def _rounding_to_32bit_signed_integer(self, integer: int, is_positive: bool) -> int: |
There was a problem hiding this comment.
個人的には動名詞をメソッド名に使うのは違和感があります。私なら _round_to_32bit_signed_int にします。
There was a problem hiding this comment.
確かに、_round_とした方が良いですね。コメントありがとうございます。
|
|
||
| for i in range(index, len(s)): | ||
| if s[i] in string.digits: | ||
| result = 10 * result + int(s[i]) |
There was a problem hiding this comment.
今回の問題の出題意図は int(s[i]) を自前で実装することだと思いますね。(自戒を込めてですが)
| if index == len(s): | ||
| return 0 |
There was a problem hiding this comment.
"Read the integer" のところは while の条件でどうせ拾われるので、sign のところの if でチェックしてもよいかと思います。好みの範囲かと思います。
| sign = 1 | ||
| if s[index] == "+": | ||
| index += 1 | ||
| elif s[index] == "-": | ||
| sign = -1 | ||
| index += 1 |
There was a problem hiding this comment.
if s[index] in "+-":
if s[index] == "-":
sign = -1
index += 1などでもよいですかね。
| # Read the integer | ||
| value = 0 | ||
| while index < len(s): | ||
| if s[index] not in string.digits: |
There was a problem hiding this comment.
感覚的に s[index].isdigit() の方をよく使う気がします。実装を見てこの書き方と違いがあるのか調べてみてもいいかもしれません。
https://docs.python.org/ja/3.13/library/stdtypes.html#str.isdigit
There was a problem hiding this comment.
一応以下のような違いを想定して書いてます。
import string
# 半角
print("1".isdigit()) # True
print("1" in string.digits) # True
# 全角
print("1".isdigit()) # True
print("1" in string.digits) # False
# カローシュティー数字
print("੭".isdigit()) # Truehttps://docs.python.org/3/library/stdtypes.html#str.isdigit
には以下のようにあり、結構広い範囲で数字判定されそうです。
Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits.
https://docs.python.org/3/library/string.html#string.digits
はノーマルな数字のみ。
The string '0123456789'.
| if sign == 1: | ||
| if value > MAX_INT // 10: | ||
| return True | ||
| if value == MAX_INT // 10 and digit > MAX_INT % 10: | ||
| return True | ||
| else: | ||
| if value < (MIN_INT + 9) // 10: | ||
| return True | ||
| if value == (MIN_INT + 9) // 10 and digit > (10 - MIN_INT % 10) % 10: | ||
| return True | ||
| return False |
There was a problem hiding this comment.
is_overflow = result > INT_MAX // 10 or (result == INT_MAX // 10 and digit > INT_MAX % 10)などとまとめることはできますね。意図的に分けたのかもしれませんが、個人的には特にマイナスのときが読みづらく感じました。。
There was a problem hiding this comment.
ご提案としては sign == 1 の場合に記載いただいた is_overflow を返り値にできるということであっていますか?
This Problem
8. String to Integer (atoi)
Next Ploblem
6. Zigzag Conversion
言語: Python