If the input for the generator can be any function, how are we supposed to check that the input for the function(the next item in the iterator) is proper? we don't which function we'll get…
Date: 09 Jan 2012 00:51
Number of posts: 6
RSS: New posts
That's the whole point.. you receive the function as a parameter, so you can execute it without knowing what it does.
def FunctionRunner(n, func): """ Gets a number and a function, runs function with number """ return func(n) FunctionRunner(5, is_prime) >>> True FunctionRunner(7,divides_by_2) >>> False FunctionRunner(5, print) >>> 5 FunctionRunner(8, lambda x: x>20) >>> False
So 'FunctionRunner' can run any matching function you throw at it, without knowing what it is or what it's supposed to do.
Your generator should act in a similar way
We also saw examples in the recitation for running an unknown function, when we learnt about lambda expressions and defined a function's derivative without knowing the function
Oh, I think you were asking how can we make sure that the function can *accept* the argument - In that case, I just guess we can assume its validity.
It's not your fault if a user executes:
def dividing_ten(n): return 10%n == 0 takewhile(dividing_ten, iter())
(Which will divide by zero and crash)
But wait for a staff confirmation to make sure I'm right..
1. so we don't need to check validity of the argument? because after i asked the question i thought about a good way to do it- with "try" and "except".
2. if there is no item in the iterator that holds the condition "pred" (that pred(iterator)= True), is it ok that an error "StopIteration" is returned? or do we need to avoid the error with "try" also?
Thanks Roi for the help!
Just don't 'yield'.
I checked it - if the method has a 'yield' statement, it returns a generator without running at all.
Only when you ask the generator for 'next', it'll start running, and if no yield is actually called - the StopIteration will come by itself.