User Tools

Site Tools


python:index

This is an old revision of the document!


Python

from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
 
def shred_unicode(s):
	return unicodedata.normalize('NFKD', s.decode("utf-8")).encode('ascii','ignore')
 
import itertools
def sliding_window(seq, n=2, pad_value=None, pad_left=0, pad_right=0):
	"Returns a sliding window (of width n) over data from the iterable."
	"Can optionally pad the window left and right."
	it = itertools.chain(
		itertools.repeat(pad_value,pad_left), 
		seq, 
		itertools.repeat(pad_value,pad_right),
	)
	#it = iter(seq)
	result = tuple(itertools.islice(it, n))
	if len(result) == n:
		yield result    
	for elem in it:
		result = result[1:] + (elem,)
		yield result
 
def open_dash(filename,mode='r',bufsize=-1):
	if filename == '-':
		if 'w' in mode  or  'a' in mode: return sys.stdout
		elif 'r' in mode:                return sys.stdin
		else:                            raise Exception("Bad mode")
	else:
		return open(filename,mode,bufsize)
 
# allows you to put color codes in backticks and have them turned into escape codes
# example: colorize("`31`red `44`on blue`` reset")
# if enable is set to False, then backticked numbers are merely removed instead of being colorized
def colorize(s,enable=True): return re.sub('`(.*?)`','\x1b[\\1m',s) if enable else re.sub('`(.*?)`','',s)
 
# a decorator that puts the given function into a dictionary, changing its name:
heuristics = {}
def heuristic(func):
	name = func.__name__.replace('gadget_is_','').replace('gadget_','').replace('_','-')
	heuristics[name]=func
	return func
 
def uniq(seq, idfun=None): 
    # order preserving
    if idfun is None: idfun = lambda x: x
    seen = {}
    result = []
    for item in seq:
        marker = idfun(item)
        if marker not in seen: 
			seen[marker] = 1
			result.append(item)
    return result
 
def product(L): return reduce(lambda x,y: x*y, L, 1)
python/index.1345064001.txt.gz · Last modified: 2012/08/15 13:53 by tkbletsc

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki