Skip to content

{ Monthly Archives } November 2007

Exceptions

Ned Batchelder has written a concise tutorial on the use of exceptions in Python. A slight improvement would be to illustrate the creation of new exception classes. Will do that here if time allows. Consider the following:
import exceptions
import pprint

class MyException(exceptions.Exception):
def __init__(self, value, **kwargs):
self.value [...]

Ubuntu Gutsy

I’ve migrated most of the desktops in the organization to Gutsy Gibbon. Flawless installs. Granted, I do the following to make sure this is the case:
keep /home on a separate partition
Install non-standard apps in a separate partition (e.g. /opt)
Use the following to keep a list of what packages you need/like:
dpkg –get-selections | grep -v deinstall [...]

Combinatorics

Jack Diederich has written a nice C extension for combinatorics. Fast and pythonic. A big problem with many pure python implementations is that they are just too slow for realistic inputs. Consider that the output in this class of problem grows factorially, it’s easy to understand why python will be slow. The C extension [...]

Alphabetic Sort

Short and sweet exposition on alphabetic sort. Using Python 2.4-3 and higher, you can use the sort(key=xxx) syntax. Rather than preserving the stable sort, the key=lambda s: (s.lower(), s) will sort lowercase then uppercase.
>>> items=['greg','Car','car','Goose']
>>> items.sort(key=lambda s: (s.lower(), s))
>>> items
['Car', 'car', 'Goose', 'greg']
>>> items=['greg','Car','car','Goose'][::-1]
>>> items.sort(key=lambda s: (s.lower(), s))
>>> items
['Car', 'car', 'Goose', 'greg']

Generating combinations (Cartesian Products)

George Sakkis has a useful algorithm for generating combinations:
from itertools import islice, repeat, izip, cycle

# If PEP 3102 is accepted, the signature would be
#def iterCombinations(*iterables, blocksize=1):
def iterCombinations(*iterables, **kwds):
”’Generates the combinations of the given iterables.

@returns: An iterator over all combinations of the C{iterables}. Each yielded
[...]

A generator for an arbitrary number of ‘for’ loops

Colin Gillespie came up with a useful generator for use when you are tempted by nested for loops:
from copy import copy

def mrange(min_values, max_values=None):
”’
Inputs: min_values, a list/tuple with the starting values
[...]

Sorting list of objects on arbitrary attribute

Max M wrote a nice little comparator for sorting:
class sortClass:

“”"
Sorts list on one or more attributes.
If attribute is callable it sorts on the result
“”"

def __init__(self, attributes, ignoreCase=1):
[...]

Consultingware

Joel Spolsky has a good description of what happens when expectations do not match delivery:

Custom development is that murky world where a customer tells you what to build, and you say, “are you sure?” and they say yes, and you make an absolutely beautiful spec, and say, “is this what you want?” and they say [...]