So I have an assingment that I am stuck on -_-

So I am supposed to create a code that "tests" out a range of integers and determine the perfect squares(4,16,25, etc) within the range without using square root calculations and using a function. I have written the following, and after staring at it for 4 hours, I can't find my mistake in generating the squares.

Any help would be appreciated ^^

``````import sys

def squares(num):
i = 1
s = 0
while s <= num :
s = (i * i)
i = i + 1
return s

start = input ("Enter a starting value:   ")
stop = input ("Enter an ending value:   ")

if start < 1 :
print ("Starting value is too low")
exit()
else :
num = start
while num <= stop:
squares(num)
if num == squares(num):
print squares(num)
else :
num = num
num = num + 1``````
4
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by pyTony

squares() never saves or prints the perfect squares within the while loop, (or tests if the arg "num" is ever found as a perfect square if that is what you want to do. I can't tell as there are no comments in the code). Add a print statement which will tell you that the problem is with incrementing.

``````def squares(num):
i = 1
s = 0
while s <= num :
s = (i * i)
print "testing", i, s, "compared to", num
i = i + 1
return s
##
## also, you have redundant code, i.e calling squares several times
while num <= stop:
ret_s = squares(num)
if num == ret_s:
print ret_s
##  the else statement does nothing
##        else :
##            num = num
num = num + 1``````

Edited by woooee: n/a

``````import sys

def is_square(num):
for x in range(num):
if x*x==num:
return True
return False

start = input ("Enter a starting value:   ")
stop = input ("Enter an ending value:   ")

print start
if start < 1 :
print ("Starting value is too low")
exit()
else :
squares = []
for x in xrange(start, stop+1):
if is_square(x):
squares.append(x)

print squares``````

I would say it like this.

``````def is_square(num):
for x in range(num+1):
if x*x >= num:
return x*x == num

for number in (1, 2, 15, 191, 121, 26, 36,  24, 25):
print '%s is %ssquare.' % ( number, '' if is_square(number) else 'not ')``````

TY ALL for your codes ^^
I think I found the error in mine.

Line 21- since it starts our false, it just skips on to the else statement and never printing anything.

Thanks

AS you mentioned "generating squares", so here still the generator of squares by using the (n + 1) ** 2 - n ** 2 = 2 * n + 1 identity:

``````def squares(n=0):
nsq = n * n
while True:
yield nsq
nsq += 2 * n + 1
n += 1

limit = 10000
for square in squares():
print '%7i' % square,
if square > limit:
break``````

Edited by pyTony: n/a