Skip to content

Instantly share code, notes, and snippets.

View hltbra's full-sized avatar

Hugo Lopes Tavares hltbra

View GitHub Profile
@hltbra
hltbra / pip-test-package-requirements.txt
Created March 29, 2013 16:07
requirements.txt for pip tests, using only pip-test-package as tarball from master
https://github.com/pypa/pip-test-package/archive/master.tar.gz#egg=pip-test-package
import sys
from setuptools import setup
deps = []
if sys.version_info >= (3,):
deps.append('DEPENDENCY_A')
else:
deps.append('DEPENDENCY_B')
class Greeting(object):
def __init__(self, msg):
self.msg = msg
def greet(self):
return 'Hello %s!' % msg
class Person(object):
def __init__(self, name):
self.name = name
people = [Person('hugo'), Person('igor')]
for p in people:
print p.name
@hltbra
hltbra / optimization.py
Created November 22, 2012 20:01
tail call optimization decorator
import sys
def tail_recursion_with_stack_inspection(g):
'''
Version of tail_recursion decorator using stack-frame inspection.
'''
loc_vars ={"in_loop":False,"cnt":0}
def result(*args, **kwd):
if not loc_vars["in_loop"]:
@hltbra
hltbra / fat.py
Created November 22, 2012 19:56
fatorial com tail recursion optimization
def fat(n):
if n == 0:
result = 1
else:
result = n * fat(n - 1)
return result
"""
fat(5)
5 * fat(4)
@hltbra
hltbra / fib.py
Created November 22, 2012 18:18
fibonacci com memoizatino
import timeit
def memoize(fn):
cache = {}
def newfn(arg):
if arg in cache:
return cache[arg]
else:
cache[arg] = fn(arg)
@hltbra
hltbra / sort.py
Created November 22, 2012 17:31
sort by
import pprint
pessoas = [
{'nome': 'Adolfo', 'estado': 'MG'},
{'nome': 'Igor', 'estado': 'CE'},
{'nome': 'Pedro', 'estado': 'RS'},
{'nome': 'Maria', 'estado': 'AC'},
]
def por_nome(pessoa1, pessoa2):
@hltbra
hltbra / runlength.py
Created November 20, 2012 13:28
run length encoding using recursion
def encode(text):
if not text:
return ""
else:
last_char = text[0]
max_index = len(text)
i = 1
while i < max_index and last_char == text[i]:
i += 1
return last_char + str(i) + encode(text[i:])
@hltbra
hltbra / mergesort.py
Created November 20, 2012 13:07
mergesort using imutability
# using tail recursion
def merge(l, r, acc):
if not l:
return acc + r
elif not r:
return acc + l
if l[0] < r[0]:
return merge(l[1:], r, acc + [l[0]])
else: