#!/usr/bin/env python # coding: utf-8 # # Algunas perlitas # ## Generadores # ![](https://upload.wikimedia.org/math/e/b/9/eb920c7c414aba2f2c80d988e8f948eb.png) # ![](https://upload.wikimedia.org/math/7/2/d/72db5b80fab995f7235d4922d559d783.png) # ![](https://upload.wikimedia.org/math/6/a/2/6a26a5dd3bf2e82f1818beac0032d4ad.png) # In[1]: def fibonacci(n): valores = [] a, b = 0, 1 while len(valores) < n: valores.append(b) a, b = b, a + b return valores # In[2]: fibonacci(10) # In[3]: get_ipython().run_line_magic('timeit', 'fibonacci(1000)') # In[4]: def fibonacci_gen(n): a, b, i = 0, 1, 0 while i < n: yield b a, b = b, a + b i += 1 # In[5]: fibonacci_gen(10) # In[6]: get_ipython().run_line_magic('timeit', 'fibonacci_gen(1000)') # # List Comprehensions # In[7]: valores = [3, 4, 1, 8, 12, 92, 34, 1, 52, 11, 8] # In[8]: [x ** 2 for x in valores] # In[9]: [x ** 2 for x in valores if x < 15] # # Espacio de nombres # In[10]: def funcion(x, y): print(x, y) # In[11]: funcion(3, 4) # In[12]: x = 5 def funcion(x, y): print(x, y) # In[13]: funcion(3, 4) # In[14]: z = 5 def funcion(x, y): global z z = 8 print(x, y) # In[15]: print(z) # In[16]: funcion(3, 4) # In[17]: print(z) # # Context Managers # In[18]: get_ipython().run_cell_magic('file', 'usuarios.csv', 'juan,gonzalez,33\npedro,martinez,24\nsusana,romero,54\n') # In[19]: 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])) # # Decoradores # In[20]: def alcubo(n): return n ** 3 # In[21]: alcubo(5) # In[22]: 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 # In[23]: @log def alcubo(n): return n ** 3 # In[24]: alcubo(5) # In[ ]: