Skip to content

Create 50. Pow(x, n).md#45

Open
tokuhirat wants to merge 1 commit into
mainfrom
50.-Pow(x,-n)
Open

Create 50. Pow(x, n).md#45
tokuhirat wants to merge 1 commit into
mainfrom
50.-Pow(x,-n)

Conversation

@tokuhirat
Copy link
Copy Markdown
Owner

This Problem
50. Pow(x, n)
Next Ploblem
779. K-th Symbol in Grammar
言語: Python

class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
return 1.0 / self.myPow(x, -n)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

x=0をケアするとより良いかと思います。

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.

ありがとうございます。組み込み関数では以下のようになっていました。
何もエラーの扱いをしないと、ZeroDivisionError: float division by zero が出力されるので、状況がわかるエラー文にしてあげると親切になると思いました。

>> pow(0, -1)
ZeroDivisionError: 0.0 cannot be raised to a negative power

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

組み込み関数でそもそもエラーを出すので特段ケアする必要はないのですね。失礼しました。

return 1 / self.myPow(x, -n)

result = 1.0
pow = x
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

後の 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
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

pow = x としているのであれば、こちら (n) についても、引数をいじっていくよりは exponent のような変数名にしたほうがよさそうです。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

x に倣って n も別変数に置き換えるというのは自分も同意です。
一方、引数をいじるということについては、参照渡しではないので問題ないかと思いました。

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.

ありがとうございます。おっしゃる通り問題はないのですが読みやすさ的には課題がありますね。

result *= base
base *= base
bit <<= 1
return result
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

'# ex) 3^5 = 3^(2^0 + 2^2) = 3^(2^0) * 3^(2^2)'
のようなコメントがあると読み手に優しいかと思いました。

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.

ありがとうございます。少なくとも repeated squaring とは書いた方が良さそうですね。

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.

4 participants