2

I have a function that can be simplified to:

def do_stuff(a,b,c):
    a = a*2
    b = b*3
    c = c
    return a, b, c

Given initial conditions: a = 2, b = 3, c = 1

I want to iterate the function until a is equal to 64

I am trying to use a while loop, something like

while True:
   new_a, new_b, new_c = do_stuff(a, b, c)

   ... Here is where I am confused ...

   if new_a = 64:
       return False

How I declare the initial values of the function then make it use its own output as input on the next iteration.

Any help is appreciated!

jpp
  • 159,742
  • 34
  • 281
  • 339
mb567
  • 691
  • 6
  • 21

3 Answers3

2

Answer to the specific question

Make your function a generator, filter with a generator expression and call next on it.

>>> def do_stuff(a,b,c):
...:    while True:
...:        a = a*2
...:        b = b*3
...:        c = c
...:        yield a, b, c
...:        
>>> next((a, b, c) for a, b, c in do_stuff(2, 3, 1) if a == 64)
>>> (64, 729, 1)

Answer to the more general question in the title for future readers

How to use the output of a function as input of a new iteration of another function?

Consider a coroutine! Here is a very basic example.

>>> def computation(x):
...:    return x%2
>>> 
>>> def consumer():
...:    while True:
...:        got = yield 
...:        print('consumer got value {}'.format(got))
...:        # do something awesome with got
...:        
>>> 
>>> cons = consumer()
>>> next(cons) # prime coroutine
>>> 
>>> for i in range(3):
...:    cons.send(computation(i))
consumer got value 0
consumer got value 1
consumer got value 0

If you want to learn more about coroutines, have a look at this excellent presentation by David Beazley.

timgeb
  • 76,762
  • 20
  • 123
  • 145
1

If you're looking for a plain iterative solution, try this.

def do_stuff(a,b,c):
    a = a*2
    b = b*3
    c = c
    return a,b,c

a,b,c = (2,3,1)
while a != 64:
    a,b,c = do_stuff(a,b,c)
Ian McLaird
  • 5,507
  • 2
  • 22
  • 31
0

You can use a recursive function with an if statement:

def do_stuff(a, b, c):
    if a == 64:
        return a, b, c
    return do_stuff(a*2, b*3, c)

a, b, c = do_stuff(2, 3, 1)

print((a, b, c))

(64, 729, 1)

See Basics of recursion in Python to understand how recursion works.

jpp
  • 159,742
  • 34
  • 281
  • 339