Conversation
| class Solution: | ||
| def myPow(self, x: float, n: int) -> float: | ||
| if n < 0: | ||
| return 1.0 / self.myPow(x, -n) |
There was a problem hiding this comment.
ありがとうございます。組み込み関数では以下のようになっていました。
何もエラーの扱いをしないと、ZeroDivisionError: float division by zero が出力されるので、状況がわかるエラー文にしてあげると親切になると思いました。
>> pow(0, -1)
ZeroDivisionError: 0.0 cannot be raised to a negative power
There was a problem hiding this comment.
組み込み関数でそもそもエラーを出すので特段ケアする必要はないのですね。失礼しました。
| return 1 / self.myPow(x, -n) | ||
|
|
||
| result = 1.0 | ||
| pow = x |
There was a problem hiding this comment.
後の step でコメントありますが、pow だと built-in と被るのと、英単語としても base とかのほうがよいかなと感じました。
https://docs.python.org/ja/3.13/library/functions.html#pow
| result *= pow | ||
| pow *= pow | ||
| # pow **= 2 このようにすると OverflowError | ||
| n //= 2 |
There was a problem hiding this comment.
pow = x としているのであれば、こちら (n) についても、引数をいじっていくよりは exponent のような変数名にしたほうがよさそうです。
There was a problem hiding this comment.
x に倣って n も別変数に置き換えるというのは自分も同意です。
一方、引数をいじるということについては、参照渡しではないので問題ないかと思いました。
There was a problem hiding this comment.
ありがとうございます。おっしゃる通り問題はないのですが読みやすさ的には課題がありますね。
| result *= base | ||
| base *= base | ||
| bit <<= 1 | ||
| return result |
There was a problem hiding this comment.
'# ex) 3^5 = 3^(2^0 + 2^2) = 3^(2^0) * 3^(2^2)'
のようなコメントがあると読み手に優しいかと思いました。
There was a problem hiding this comment.
ありがとうございます。少なくとも repeated squaring とは書いた方が良さそうですね。
This Problem
50. Pow(x, n)
Next Ploblem
779. K-th Symbol in Grammar
言語: Python