Feed on
Posts
Comments

Archive for the 'Python' Category

get timestamp in python

to insert a timestamp into your python code: import time …. print time.localtime()

measure python’s memory usage

profiling running time in python is straightforward.  what’s tricky is measuring how much memory your program is consuming.  i’ve modified some code i found online to do the trick nicely; just import this PyVM module and insert the following into your program: import PyVM … PyVM.MemoryUpdate(“memory usage here”) PyVM.MemoryUpdate(“memory usage there”) PyVM.MemoryUpdate(“memory usage etc.”) what […]

do fast intersections in python

let’s say you’ve got two lists creatively named: list1 & list2, and you’d like their intersection. an easy way to get this intersection would be to iterate through both lists: intersect = filter(lambda i: i in list1,list2) this is slow though for large lists, as it takes roughly M X N steps, where M and […]

here’s how to extract every other element from a python list using one line of code. to get even elements, use “i%2 == 0″; for odd elements, use “i%2 == 1″. >>> my_list = ['banana','apple','frog','octopus','pen','spiderman','flower','battery'] >>> map(lambda i: my_list[i],filter(lambda i: i%2 == 0,range(len(my_list)))) ['banana', 'frog', 'pen', 'flower'] >>> map(lambda i: my_list[i],filter(lambda i: i%2 == 1,range(len(my_list)))) […]

flush write buffer in python

to flush a write buffer in python on filehandle f: f.flush() nice and easy …

to write out a matrix from python’s numpy: import numpy numpy.savetxt(matrix_filename,matrix_object) to read a matrix from numpy: import numpy matrix_object = numpy.genfromtxt(matrix_filename)

to write a python dict to a text file: f = open(‘text.file’,’w’) f.write(my_dict) to read a python dict from a text file: f = open(‘text.file’,’r’) my_dict = eval(f.read())

hash a set in python

to hash a set in python, you need to make it immutable: from sets import Set … this_set = frozenset(i) my_dict[this_set] = 1

as long as you’re running a version of python newer than 2.3, you can easily call the python profiler to find bottlenecks in your code: $ python -m cProfile mycode.py

if your python code produces the following error: “RuntimeError: maximum recursion depth exceeded in cmp,” try adding this line to the beginning of your code: sys.setrecursionlimit(1500) note that python’s default limit is 1000.

« Prev - Next »