User Tools

Site Tools


python:index

This is an old revision of the document!


Python

def avg(v): return sum(v)/len(v)
def stdev(v): return math.sqrt(sum(x*x for x in v) / len(v) - (avg(v) ** 2))
def pct_diff(a,b): return (a/b)-1
def product(L): return reduce(lambda x,y: x*y, L, 1)
 
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')
 
# divide a list into equal pieces.  
# chunk ranges from 0 to num_chunks-1
def divide_list(lst,chunk,num_chunks):
	i = int( float(chunk)/num_chunks*len(lst) )
	j = int( float(chunk+1)/num_chunks*len(lst) )-1
	return lst[i:j]
 
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
 
# unlike set(), this is order preserving
def uniq(seq, idfunc=None): 
	seen = set()
	for item in seq:
		marker = idfunc(item) if idfunc else item
		if marker not in seen: 
			seen.add(marker)
			yield item

Drop into python shell:

import code
code.interact(local=locals())
class ConsoleThrobber(object):
	def __init__(self,chars='/\\'):
		self.chars=chars
		self.i=0
	def __call__(self):
		sys.stdout.write("\r" + self.chars[self.i])
		sys.stdout.flush()
		self.i = (self.i + 1) % len(self.chars)
 
def workload():
	throb = ConsoleThrobber("\\|/-")
	while True:
		# ... do stuff ...
		throb()
python/index.1353512466.txt.gz · Last modified: 2012/11/21 07:41 by tkbletsc

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki