'How can I write a function that returns all negative numbers as well as checks if the input are only integers and floating point numbers? [duplicate]
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 1:[1]
You're on the right track; you just need to make a loop for type comparisons:
# (...)
else:
for num in l:
if type(num) not in (int, float):
return "Invalid parameter type!"
# (...)
Solution 2:[2]
You can achieve what you are looking for with:
def find_negatives(l):
if type(l) != list or any(str(x).isnumeric() for x in l) == False:
return 'Invalid parameter type!'
l_tmp = []
for num in l:
if num < 0:
l_tmp.append(num)
return l_tmp
All you have to do is check whether the input is a list and if any element of the input is not a number.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rodrigo Rodrigues |
Solution 2 |