Issue
#How should I eliminate those string elements like "4" and "5"? #
The ideal output or results should be like below:
>>> filter_positives_from_args(-3, -2, -1, 0, 1, 2, 3)
[0, 1, 2, 3]
>>> filter_positives_from_args(-3, -2, -1, 0, 1, 2, 3, '4', '5')
[0, 1, 2, 3]
>>> filter_positives_from_args(-3, -2, -1, False, True, 2, 3, '4', '5')
[False, True, 2, 3]
My code:
def filter_positives_from_args(*args) -> list:
ans = [p for p in args if int(p) >= 0]
return(list(filter(None,ans)))
My output:
>>> print(filter_positives_from_args(-3, -2, -1, 0, 1, 2, 3))
[1, 2, 3]
>>> print(filter_positives_from_args(-3, -2, -1, 0, 1, 2, 3, '4', '5'))
[1, 2, 3, '4', '5']
>>> print(filter_positives_from_args(-3, -2, -1, False, True, 2, 3, '4', '5'))
[True, 2, 3, '4', '5']
How to solve this problem?
Solution
You just need to also check the type of each argument:
def filter_non_negatives(*args):
valid_types = {bool, int, float, complex}
return [p for p in args if type(p) in valid_types and p >= 0]
Note that I've changed the name of the argument to be more accurate, as explained in my comment.
Answered By - ddejohn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.