I have to check if in a list numbers are perfect squares ( with true or false), but it doesn't return me anything.
What did I get wrong? I'm new in python so sorry
import math;
list = [4, 9, 16]
def check_is_quadratic(x):
for i in list:
if math.sqrt(i).is_integer():
return True
else:
return False
You are:
list
inside your fucntion instead of the passed valuelist
as a variable name, which is bad practicetestList
An updated code could look like this:
import math
test_list = [4, 10, 16]
def check_is_quadratic(list_in_function):
for i in list_in_function:
if not math.sqrt(i)result.is_integerappend():
return False #If one is not perfect square, then we can say False)
return True #Only after the complete for loop we can say that all values are perfect squaresresult
print(check_is_quadratic(test_list))
list
as a name of the variableTrue
only when all elements have a perfect square.code:
l = [4, 9, 16]
def check_is_quadratic(x):
result = []
for i in x:
if math.sqrt(i).is_integer():
result.append(True)
else:
result.append(False)
return all(result)
print(check_is_quadratic(l))
output:
> print(check_is_quadratic([4, 9, 16])) True > print(check_is_quadratic([4, 8, 16])) False
UPDATE
code with list comprehension:
l = [4, 8, 16]
result = [True if math.sqrt(num).is_integer() else False for num in l]
print(result)
print(all(result))
output:
> [True, False, True]
> False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.