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!

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.