# ptools (p wie pirx) # # Just some little helpers which don't fit elsewhere, # posted for review """ Pirx Tools V0.0 timing measure time behavior of some function sort "Schwartzian Sort" and stable sort together transpose very fast transpose """ def timing(func, args=None, n=1, **keywords) : import time time=time.time appl=apply if args is None: args = () if type(args) != type(()) : args=(args,) rep=range(n) dummyarg = ("",) dummykw = {} dummyfunc = len if keywords: before=time() for i in rep: res=appl(dummyfunc, dummyarg, dummykw) empty = time()-before before=time() for i in rep: res=appl(func, args, keywords) else: before=time() for i in rep: res=appl(dummyfunc, dummyarg) empty = time()-before before=time() for i in rep: res=appl(func, args) after = time() return round(after-before-empty,4), res # this is taken from the FAQ and modified slightly: """ 4.51. I want to do a complicated sort: can you do a Schwartzian Transform in Python? Yes, and in Python you only have to write it once: def st(List, Metric): def pairing(element, M = Metric): return (M(element), element) paired = map(pairing, List) paired.sort() return map(stripit, paired) def stripit(pair): return pair[1] """ # now, this is my version: def sort(List, Metric=None, stable=1) : """sort a list by a given metric function. The sort defaults to be stable, keeping the order of elements which cannot be distinguished by the metric""" # transpose has problems with small lists, but in that # case we don't need it: if len(List) < 2: return List[:] shaker = [List] where = 0 if Metric : # sorter is a list of function results shaker.insert(0, map(Metric, List)) where = -1 # we are at the end if stable : # always stabilize behind the key shaker.insert(1, range(len(List))) # and we are still either at front or end shaker = transpose(shaker) shaker.sort() return list(transpose(shaker)[where]) def transpose(x) : """transpose a sequence of lists into a list of tuples. This is very fast, but doesn't work for len(x)==1""" return apply(map, (None,)+tuple(x)) # Special problem with fast transpose: # Due to map, transpose of a list with a single element # returns a list, shape is lost. # Solution: def transpose(x) : if len(x) == 1 : return map(lambda y : (y,), x[0]) return apply(map, (None,)+tuple(x)) # General problems with transpose (not solvable here): # A list of empty tuples returns an empty list (shape lost) #EOModule :-)