Can parameters be passed to a function its own return value?

2

Hi, I'm trying to do a filter but I need the filter output data to go through the N times filter again, until I get the data I'm looking for. But can this be done in python? I need to do it with the use of calls to a filter function determined by me, ie     def filter (x, y)     calculations     return (p, q)

and then the same filter takes p, that is to say     def filter (p, q)     calculations     return (m, l) Is it possible to do this is python? and if possible? as I would do to raise it thank you very much ..

    
asked by Loreisiss 07.07.2018 в 01:59
source

1 answer

2

You can simply use an iterative approach using a cycle, for example with a for you can have it apply n times the function:

def foo(p, q):
    p += 1
    q += 5 
    return p, q

p = 14
q = 23
for _ in range(5): 
    p, q = foo(p, q)  

If the number of iterations is indeterminate and depends on a certain condition, use a while :

def foo(p, q):
    print("Valor de p:", p)
    p += 1 
    return p, q

p = 1
q = 5
while p != q:
    p, q = foo(p, q)

You can create a function that allows you to execute n times any function with an indeterminate number of positional arguments (which logically can be fed back with its own output):

def repetir(func, veces, *args):
    if not args:
        for _ in range(veces):
            func()

    elif len(args) == 1:
        arg = args[0]
        for _ in range(veces):
            arg = func(arg)
        return arg

    else:
        for _ in range(veces):
            args = func(*args)
        return args

def foo(p, q):
    p += 1
    q += 5 
    return p, q

def cuadrado(n):
    return n * n
>>> repetir(foo, 4, 2, 13)
(6, 33)
>>> repetir(cuadrado, 4, 2)
65536
    
answered by 07.07.2018 / 03:16
source