I'm tryng to learn different ways to do simple things in python, while also learning a bit about some functional practices. I have some numbers that the user inputs, and I want to know if they really are numbers. I've come up with this kind of classic solution:
def foo(list_of_inputs):
for n in list_of_inputs:
if not hasattr(n, "real"):
# some number is not a number!
return False
# all are numbers
return True
But then, I figured out this other "thing" that may have some potential:
def foo(list_of_inputs):
bool_list = map(lambda input: hasattr(input, "real"), list_of_inputs)
return reduce(lambda x, y: x == y, bool_list)
I think that maybe a function that returns "True" if all members of a collection, iterable, or whatever the correct concept I'm looking for, are "True", may already be something somewhat common, and also, this second attempt doesn't return when a "False" is found, while the classic one does... But I find it elegant, and maybe that is because I'm not there yet with programming in general.
So my question is: what's the "probably better" way to do this?
As mentioned, the
all
function will do what you want. What you describe you're trying to do can also be done with thestr.isnumeric()
function.Edit: I'm finding that it fails on
['1','2','3.14','4']
which is a little annoying. Maybe someone can come up with a cleverer solution than this, but I decided to wrap a slightly modified approach in atry
:That works on: