Dejell
Dejell

Reputation: 14317

yield python add previous function result

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.

Upvotes: 2

Views: 138

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

Save the value each time.

def my_function(f, value):
  yield value
  while True:
    value = f(value)
    yield value

Upvotes: 5

Related Questions