Question

I want to write a function that would use yield , but every time the value of the field to send to the function would be the previous result:

for instance, if the call to

f(5) returns 10, the next call would f(10). if the result of f(10) returns 18 the next call will be f(18)

How can I do it? I wrote this code:

def my_function(f,init_value):
  yield init_value
  while True:
     yield f(init_value)

But it always returns the call to f(init_value) and not as I would expect.

Was it helpful?

Solution

Save the value each time.

def my_function(f, value):
  yield value
  while True:
    value = f(value)
    yield value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top