Question: Write a function valid(f, l) that, given a function f and a list of potential inputs l, returns a list, tuple, or set of the
Write a function valid(f, l) that, given a function f and a list of potential inputs l, returns a list, tuple, or set of the elements of l that are valid inputs to f. How will you know if something is a valid input to f? If you call f on the element and an exception is thrown, you know it was not a valid input--review practice question 3 where we try to use the hex2dec() function, but ignore any error we get if the input was not valid.
For instance, if f is the abs() function, it can only accept integers and floating point numbers. If it is the max() function, it can only accept lists or tuples, if it is the sqrt() function, it can only accept non-negative numbers, etc...
from math import sqrt valid(sqrt, [-3, 0, 5]) == [0, 5]
from math import asin valid(asin, [0.3, -0.1, -1, 1, 'cat', '1', 1.3]) == [0.3, -0.1, -1, 1]
valid(chr, [-1, 10, 123.3, 2**21]) == [10]
def onlyStrings(x): if type(x) == str: return True else: raise UserWarning
valid(onlyStrings, ['cat', 123, [1, 2, 3]]) == ['cat']
Step by Step Solution
There are 3 Steps involved in it
To solve this problem we need to write a function validf l that filters a list l to only include elements that can be successfully used as inputs to t... View full answer
Get step-by-step solutions from verified subject matter experts
