Reputation: 39
The code below prints out the numbers that are perfect squares. I am having trouble displaying the amount of perfect squares I have in my list. It should return 3.
squares( [[1,2,3],[4,5],[6,7,8,9]])
The implementation is below:
def squares(square):
for row in square:
for col in row:
if col**0.5%1 ==0:
print(col)
Upvotes: 0
Views: 62
Reputation: 1626
You can use the list comprehension as :
len([x for row in square_list for x in row if math.sqrt(x)%1==0])
or you can use the normal function :
import math
def squares(square_list):
count = 0
for row in square_list:
for col in row:
if math.sqrt(col)%1 ==0:
count+=1
return count
Upvotes: 1
Reputation: 5479
Here it is. Accumulate your perfect squares in a list and finally print the length of the list and its contents as below:
def squares(square):
result = []
for row in square:
for col in row:
if col**0.5%1 ==0:
result.append(col)
print(f'There are {len(result)} perfect squares: {result}')
squares( [[1,2,3],[4,5],[6,7,8,9]])
#Prints: There are 3 perfect squares: [1, 4, 9]
Upvotes: 0
Reputation: 199
You need to save count of correct outcomes (count
)
def squares(square):
count = 0
for row in square:
for col in row:
if col**0.5%1 ==0:
count+=1
return count
Upvotes: 0