For loop trick in Python

december 3, 2008

More languages should have this Python feature:

for i, x in enumerate(a):
    print "object at index ", i, " is ", x

Very often we need both the item in an array and its index, but no, most language require us to either use for loop and get the item by array[index] or implement a counter as the following

i = 0
for x in a:
    print "object at index ", i, " is ", x
    i = i + 1

I like Python.

Is it Easter yet?

juli 22, 2008

One of my colleagues wanted to know if it was possible to figure out if a given date is a business day. Saturday, Sunday are easy, they’re never a business day. Christmas, easy always the same date, actually it’s only the Christian holidays in the spring time that posses a problem. This is because they’re all determined by when Easter falls, and Easter being the first Saturday after the first full moon after or on March the 21st, which means that it does fall on the same date every year. I thought it would be hard to figure out, but as it turns out, it’s a solved problem. Many programming languages and frameworks have methods for getting the date of Easter, and if not, the math really isn’t hard to implement.

My implementation (in Python):
holiday.py

Ezmlm hash for Python

juli 21, 2008

I don’t have any real use for this anymore, but I do remember administrating a qmail + ezmlm mailserver and being annoyed that only PHP had ezmlm hash implemented. The hash isn’t really documented anywhere that I find, but the ezmlm C code is available, as is the PHP implementation and most resently someone wrote the Ruby code for the hash (DZone Snippets).

From the C and Ruby implementations I managed to hack together a Python version. Honestly it’s a bit weird and I would have preferred the documentation for the hash, so that I could be certain that my implementation will always do the right thing.

def ezmlm_hash(addr):
  h = 5381
  for c in addr:
    h = ((h + (h << 5)) ^ ord(c)) % (2 << 31)
  h = h % 53
  return h
Follow

Get every new post delivered to your Inbox.