[Tutor] iscube function
Terry Carroll
carroll at tjc.com
Wed Apr 11 02:11:03 CEST 2007
On Tue, 10 Apr 2007, Robert William Hanks wrote:
> how is the best way to find out if a number is a perfect cube in python?
> i am working if integer numbers only. i am asking because
> pow(1728, 1.0/3.0) --> 11.999999999999998
def iscube(n):
cubed_root = n**(1/3.0)
if round(cubed_root)**3 == n:
return True
else:
return False
if __name__ == "__main__":
rootlim = 20
calculated_cubes = [n**3 for n in range(1,rootlim+1)]
found_cubes = [n for n in range(1, rootlim**3+1) if iscube(n)]
if found_cubes == calculated_cubes:
print "Hey, it worked!"
else:
print "Oops."
missed_cubes = [n for n in calculated_cubes if n not in found_cubes]
wrong_cubes = [n for n in found_cubes if n not in calculated_cubes]
print "missed cubes:", missed_cubes
print "wrong cubes:", wrong_cubes
More information about the Tutor
mailing list