Raised This Month: $51 Target: $400
 12% 

Funciones recursivas e iterativas


  
 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
Author Message
Neeeeeeeeeel.-
Some Guy Yellin'
Join Date: Jul 2010
Location: Argentina
Old 04-17-2013 , 21:46   Funciones recursivas e iterativas
#1

Según explicó mi profesora de programación una función recursiva es aquella que se llama así misma tantas veces como sea necesario para lograr algo. Y una funcion iterativa es un bucle (for o while) que tambien se repite para lograr algo.

Según ella es mucho mas útil una función recursiva que hacerlo con un bucle, lo cual no estoy de acuerdo y hago este thread para que dejen sus opiniones y fundamentos aver si puedo aclarar un poco mi duda.

Voy a dar dos ejemplos simples hechos en python.
HTML Code:
def max_value_iterativa( nList ):
    
    output = nList[ 0 ];

    for i in nList:
        
        if i > output:
            output = i;
            
    return output;
    
def max_value_recursiva( nList, CurrentValue = 0, output = 0 ):
    
    if nList[ CurrentValue ] > output:
        output = nList[ CurrentValue ];
    
    if len( nList ) > CurrentValue + 1:
        return max_value_recursiva( nList, CurrentValue + 1, output );
    
    else:
        return output;
Un ejemplo de como llamar a estas funciones es:
HTML Code:
lista = [ 0, 20, 15, 35, 2 ];
print max_value_iterativa( lista );
print max_value_recursiva( lista );
Para llegar a que es mas eficiente usar la iteración que la recursión lo que hize fue pensar como las 2 funciones se almacenan en memoria.

La función iterativa: Se carga el bloque en memoria de la funcion en memoria una sola vez y cuando termina se borra de la memoria.

La función recursiva: Por cada item de la lista se va a cargar el bloque de la función en memoria. O sea que si tengo 5 valores en la lista y el bloque (por dar un ejemplo) ocupa 100B en memoria, en el momento que estén los 5 bloques simultaneamente en memoria se van a ocupar 500B de memoria.
Y en la función iterativa solo se carga una vez en memoria.

Vuelvo a preguntar, ¿Tengo razón?
__________________
Neeeeeeeeeel.- is offline
Send a message via Skype™ to Neeeeeeeeeel.-
 



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 03:10.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode