The Python Oracle

Python: Function to determine if number is square, cube, etc

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping

--

Chapters
00:00 Question
01:04 Accepted answer (Score 8)
01:37 Thank you

--

Full question
https://stackoverflow.com/questions/4535...

Accepted answer links:
[Is floating point math broken?]: https://stackoverflow.com/questions/5880...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #algorithm #function #math #division

#avk47



ACCEPTED ANSWER

Score 8


Floating point arithmetic is not exact--see Is floating point math broken?.

So check your answer using exact-integer math. Round r to the nearest integer then see if the power works. This Python 3 code removes some of your redundant type-casting. For Python 2, wrap the calculation of r into an int() typecast (which is not needed for Python 3).

def is_power(N, n):
    r = round(N ** (1.0 / n))
    return r**n == N