The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 Python: Function To Determine If Number Is Square, Cube, Etc
00:42 Accepted Answer Score 8
01:10 Thank you

--

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

--

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