Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Squares Function

I'm writing a function that will return a list of square numbers but will return an empty list if the function takes the parameter ('apple') or (range(10)) or a list. I have the first part done but can't figure out how to return the empty set if the parameter n is not an integer- I keep getting an error: unorderable types: str() > int() I understand that a string can't be compared to an integer but I need it to return the empty list.

def square(n):

    return n**2

def Squares(n):

    if n>0:
        mapResult=map(square,range(1,n+1))
        squareList=(list(mapResult))   
    else:
        squareList=[]

    return squareList
like image 382
user2553807 Avatar asked Jul 06 '13 03:07

user2553807


2 Answers

You can use the type function in python to check for what data type a variable is. To do this you would use type(n) is int to check if n is the data type you want. Also, map already returns a list so there is no need for the cast. Therefore...

def Squares(n):
    squareList = []

    if type(n) is int and n > 0:
        squareList = map(square, range(1, n+1))

    return squareList
like image 141
Matias Grioni Avatar answered Oct 06 '22 15:10

Matias Grioni


You can chain all the conditions which result in returning an empty list into one conditional using or's. i.e if it is a list, or equals 'apple', or equals range(10) or n < 0 then return an empty list. ELSE return the mapResult.

def square(n):
    return n**2

def squares(n):
   if isinstance(n,list) or n == 'apple' or n == range(10) or n < 0:
      return []
   else:
      return list(map(square,range(1,n+1)))

isinstance checks if n is an instance of list.

Some test cases:

print squares([1,2])
print squares('apple')
print squares(range(10))
print squares(0)
print squares(5)

Gets

[]
[]
[]
[]
[1, 4, 9, 16, 25]
>>> 
like image 45
HennyH Avatar answered Oct 06 '22 14:10

HennyH