def fibonacci(n):
valores = []
a, b = 0, 1
while len(valores) < n:
valores.append(b)
a, b = b, a + b
return valores
fibonacci(10)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
%timeit fibonacci(1000)
1000 loops, best of 3: 230 µs per loop
def fibonacci_gen(n):
a, b, i = 0, 1, 0
while i < n:
yield b
a, b = b, a + b
i += 1
fibonacci_gen(10)
<generator object fibonacci_gen at 0x7f83441583f0>
%timeit fibonacci_gen(1000)
The slowest run took 30.60 times longer than the fastest. This could mean that an intermediate result is being cached 1000000 loops, best of 3: 270 ns per loop
valores = [3, 4, 1, 8, 12, 92, 34, 1, 52, 11, 8]
[x ** 2 for x in valores]
[9, 16, 1, 64, 144, 8464, 1156, 1, 2704, 121, 64]
[x ** 2 for x in valores if x < 15]
[9, 16, 1, 64, 144, 1, 121, 64]
def funcion(x, y):
print(x, y)
funcion(3, 4)
3 4
x = 5
def funcion(x, y):
print(x, y)
funcion(3, 4)
3 4
z = 5
def funcion(x, y):
global z
z = 8
print(x, y)
print(z)
5
funcion(3, 4)
3 4
print(z)
8
%%file usuarios.csv
juan,gonzalez,33
pedro,martinez,24
susana,romero,54
Writing usuarios.csv
import csv
with open('usuarios.csv', 'r') as fh:
for line in csv.reader(fh):
line = [l.capitalize() for l in line]
print('Nombre: {}\nApellido: {}\nEdad: {}\n\n'.format(
line[0], line[1], line[2]))
Nombre: Juan Apellido: Gonzalez Edad: 33 Nombre: Pedro Apellido: Martinez Edad: 24 Nombre: Susana Apellido: Romero Edad: 54
def alcubo(n):
return n ** 3
alcubo(5)
125
import time
def log(f):
def wrapper(*args, **kwargs):
st = time.time()
print('Antes: {}'.format(st))
resultado = f(*args, **kwargs)
et = time.time()
print('Despues: {}'.format(et))
print('Tiempo total: {}'.format(et - st))
return resultado
return wrapper
@log
def alcubo(n):
return n ** 3
alcubo(5)
Antes: 1432863987.6773825 Despues: 1432863987.6774247 Tiempo total: 4.220008850097656e-05
125