Write a function find_negatives that takes a list l of numbers as an argument and returns a list of all negative numbers in l. If there are no negative numbers in l, it returns an empty list.
def find_negatives(l):
l_tmp = []
for num in l:
if num < 0:
l_tmp.append(num)
return l_tmp
#Examples
find_negatives([8, -3.5, 0, 2, -2.7, -1.9, 0.0]) # Expected output: [-3.5, -2.7, -1.9]
find_negatives([0, 1, 2, 3, 4, 5]) # Expected output: []
This is part I am having trouble with below:
Write a function find_negatives2 that works the same as find_negatives with the following two additions:
If l is not a list, it returns the string "Invalid parameter type!"
If any of the elements in l is neither an integer nor a floating pointer number, it returns the string "Invalid parameter value!"
What I have so far
def find_negatives2(l):
l_tmp1 = []
if type(l) != list:
return "Invalid parameter type!"
else:
for num in l:
Examples:
find_negatives2([8, -3.5, 0, 2, -2.7, -1.9, 0.0]) # Expected output: [-3.5, -2.7, -1.9]
find_negatives2([0, 1, 2, 3, 4, 5]) # Expected output: []
find_negatives2(-8) # Expected output: 'Invalid parameter type!'
find_negatives2({8, -3.5, 0, 2, -2.7, -1.9, 0.0}) # Expected output: 'Invalid parameter type!'
find_negatives2([8, -3.5, 0, 2, "-2.7", -1.9, 0.0]) # Expected output: 'Invalid parameter value!'
find_negatives2([8, -3.5, 0, 2, [-2.7], -1.9, 0.0]) # Expected output: 'Invalid parameter value!'
I am not sure how to proceed. I am not sure how to check each type within the list
>Solution :
You can try code below:
def find_negatives2(l):
l_tmp1 = []
if not isinstance(l, list):
return "Invalid parameter type!"
else:
for num in l:
if not (isinstance(num, float) or isinstance(num, int)):
return "Invalid parameter value!"
else:
if num < 0:
l_tmp1.append(num)
return l_tmp1
assert find_negatives2([8, -3.5, 0, 2, -2.7, -1.9, 0.0]) == [-3.5, -2.7, -1.9]
assert find_negatives2([0, 1, 2, 3, 4, 5]) == []
assert find_negatives2(-8) == 'Invalid parameter type!'
assert find_negatives2({8, -3.5, 0, 2, -2.7, -1.9, 0.0}) == 'Invalid parameter type!'
assert find_negatives2([8, -3.5, 0, 2, "-2.7", -1.9, 0.0]) == 'Invalid parameter value!'
assert find_negatives2([8, -3.5, 0, 2, [-2.7], -1.9, 0.0]) == 'Invalid parameter value!'
All assertions will be validated.
Explanation
isinstance checks whether its first argument is an instance of its second argument or not. Using this function, you can check any variable type. Please note that using type(l) != list is not a good approach to check variable’s type. If you are interested to know why, this link might help you.