简体   繁体   中英

How to check if a number in a list is a perfect square?

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:

  1. Not calling your function or printing anything
  2. Using the global variable list inside your fucntion instead of the passed value
  3. Using the reserved word list as a variable name, which is bad practice
  4. Using return statement inside the if-else block here will give you only True/False once. What you want is to return True/False for each element inside your testList

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))
  • Have you called the function yet?
  • Don't use list as a name of the variable
  • Update the function to return True 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM