Reputation:
So i have created this function which takes two arguments (a function with one argument and a list). its purpose is to iterate through the list and return true if every instance of the function is True (else return False). So for my attempt i have this:
def all_iter(func, ls):
i = 0
c = True
for i in ls:
if func(ls[i]) == False:
c = False
break
return c
now these are the three examples i have used to see whether it runs properly and they should return :
>>>all_iter(lambda x: x >= 0, [1, 2, 3, 0, 4])
True
>>> all_iter(lambda x: x >= 0, [1, 2, -3, 0, 4])
False
>>> all_iter(lambda x: x % 2 == 0, [100, 10, 2022, 12])
True
Now for the first two examples the result i get when i run this are correct but for the third one i get: in all_iter if func(ls[i]) == False: IndexError: list index out of range. Can someone provide some help?
Upvotes: 0
Views: 100
Reputation: 461
You could run through the index in this way while keeping your function the same relative style if you are not comfortable with more pythonic solutions:
def all_iter(func, ls):
c = True
for i in ls:
if func(i) == False:
c = False
break
return c
print(all_iter(lambda x: x >= 0, [1, 2, -3, 0, 4]))
print(all_iter(lambda x: x % 2 == 0, [100, 10, 2022, 12]))
Which returns False and True respectfully. If you want to have the value return as a closure of all() then it would be something along this line:
def all_iter(func, ls):
return all(func(i) for i in ls)
the all closure will execute the function for each value in an inline lambda, which essentially does all your function does in a single line and returns a bool of true only if every element works with the function passed in.
Upvotes: 0
Reputation: 71454
This loop:
for i in ls:
if func(ls[i]) == False:
will only work if every element i
of ls
is also a valid index of ls
. In your first few inputs, all of the elements happened to be smaller than the length of the list, but you hit an IndexError
on the last case because the values were much larger.
What you might have meant to do is:
for i in ls:
if not func(i):
Note that there is a built-in function all
that simplifies this entire thing:
def all_iter(func, ls):
return all(func(i) for i in ls)
or equivalently with map()
:
def all_iter(func, ls):
return all(map(func, ls))
Upvotes: 2