Lilleman Rahimian
Lilleman Rahimian

Reputation: 1

Loop a function using the previous output as input

When my function foo generating a new element, I want to reuse the output and put it in foo n-times. How can I do it?

My function:

def foo(x):
    return x + 3


print(foo(1))
>>>4

For now. I'm using this method:

print(foo(foo(foo(1))))

Upvotes: 0

Views: 1127

Answers (5)

koficodes
koficodes

Reputation: 320

Another possible with lambda and reduce

Reduce function

from functools import reduce

def foo(x):
    return x + 3

print(reduce(lambda y, _: foo(y), range(3), 1))

You will get 10 as result

# y = assigned return value of foo.
# _ = is the list of numbers from range(3) for reduce to work
# 3 = n times
# 1 = param for x in foo

Upvotes: 0

Pavlo
Pavlo

Reputation: 1654

What you are searching for is called recursion:

def foo(x, n=1):
    if n == 0:
        return x
    return foo(x + 3, n - 1) 

Upvotes: 0

Synthaze
Synthaze

Reputation: 6090

def foo(x,y):
    for i in range(y):
        x = x + 3
    return x

print (foo(10,3))

Output:

19

Upvotes: 0

Chance
Chance

Reputation: 488

There are a couple ways to do what you want. First is recursion, but this involves changing foo() a bit, like so:

def foo(x, depth):
    if depth <= 0:
        return x
    return foo(x+3, depth-1)

and you'd call it like foo(1, n)

The other way is with a loop and temp variable, like so

val = 1
for _ in range(0, n):
    val = foo(val)

Upvotes: 1

zmbq
zmbq

Reputation: 39013

Use a loop for this:

value = 1
for i in range(10):
    value = foo(value)

Upvotes: 1

Related Questions