#Ejemplos en Python.
>>> def fib(n):
... if n==0 or n==1: return 1
... else: return fib(n-1)+fib(n-2)
...
>>> fib(5)
8
>>> map(fib,range(0,11))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> def fastfib(n):
... a,b=1,1
... while (b<n):
... a,b=b,a+b
... return b
...
>>> fastfib(10)
13
>>> fastfib(11)
13
>>> fastfib(15)
21
>>> fastfib(80)
89
#Pregunta: ¿qué hace fastfib con respecto a n?
>>> def nthfib(n):
... a,b=1,1
... for i in range(1,n+1):
... a,b=b,a+b
... return b
...
>>> nthfib(1)
2
>>> nthfib(2)
3
>>> nthfib(3)
5
>>> nthfib(4)
8
>>> map(nthfib,range(0,11))
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
# Pregunta: ¿coincide este resultado con aquel de fib? Corregir.
#Notar para grandes valores:
>>> nthfib(100)
927372692193078999176L
>>> nthfib(1000)
113796925398360272257523782552224175572745930353730513145086634176691092536145985470146129334641866902783673042322088625863396052888690096969577173696370562180400527049497109023054114771394568040040412172632376L
#Dándole una oportunidad al factorial de un número:
>>> def fact(n):
... if n==0: return 1
... else: return n*fact(n-1)
...
>>> fact(10)
3628800
>>> fact(30)
265252859812191058636308480000000L
#Miscelánea, listas y cadenas:
>>> ls="hola"
>>> ms=ls
>>> ls.reverse()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'reverse'
>>> ls=list("hola")
>>> ls.reverse()
>>> ls
['a', 'l', 'o', 'h']
>>> ms+ms
'holahola'
>>> ms*5
'holaholaholaholahola'
>>> ms[2]
'l'
>>> ms[2:]
'la'
>>> ms[:2]
'ho'
>>> ms=ms+ms
>>> ms[3:4]
'a'
>>> ms[3:7]
'ahol'
No hay comentarios:
Publicar un comentario