user2553807
user2553807

Reputation: 329

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

Upvotes: 5

Views: 33043

Answers (3)

Matias Grioni
Matias Grioni

Reputation: 316

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

Upvotes: 5

TerryA
TerryA

Reputation: 59974

You can not compare strings to integers as you have tried to do. If you want to check if n is an integer or not, you can use isinstance():

def squares(n):
    squareList = []
    if isinstance(n, (int, float)) and n > 0: # If n is an integer or a float
        squareList = list(map(square,range(1,n+1)))     
    return squareList

Now, if a string or a list is given as an argument, the function will immediately return an empty list []. If not, then it will continue to run normally.


Some examples:

print(squares('apple'))
print(squares(5))
print(squares(range(10)))

Will return:

[]
[1, 4, 9, 16, 25]
[]

Upvotes: 0

HennyH
HennyH

Reputation: 7944

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]
>>> 

Upvotes: 2

Related Questions