Reputation: 61
My code is
if graph == square_grid and type(math.sqrt(nodes)) is not int:
print "Your netork can't have that number of nodes"
Of course this doesn't work because math.sqrt always returns a float. How can I do this?
Upvotes: 4
Views: 1219
Reputation: 9681
Using pure maths (no libraries) a square number can be determined in Python as follows:
not n**0.5 % 1
As the square root of a square integer is an integer, this test uses modulo 1 equal to zero to test if the square root is an integer.
The following will print the first five square numbers:
for i in range(1, 26):
if not i**0.5 % 1:
print(i)
Output:
1
4
9
16
25
Upvotes: 0
Reputation: 17829
Because math.sqrt always returns a float, you can use the built in is_integer
method
def is_square(x):
answer = math.sqrt(x)
return answer.is_integer()
this will return True
if x
is a square and False
if it's not
>>> is_square(25)
True
>>> is_square(14)
False
Upvotes: 7