Python code

Sometimes I wonder what I would do without the internet  and without the free software communities that make it possible and make it big and fun. Python programming is fun because of libraries and modules contributed by the community and that allow you to do all sort of cool things. Programming is both an exercise in applied logic and an exercise in navigating the community fora for answers, hints… have you tried stack overflow?

This page is my way to give something back to the community I depend on in most of my work. Small code snippets is what I can give. They are here.

Playing with words

For the sequential innovation paper (paper, blog entry) I had to handle words, spellchecking, anagrams… So a couple of hints:

  • if you ever need spellchecking in python, try pyenchant. It is not the fastest, but it works as a charm and is dead easy to use – four lines and you have a spellchecker function.
  • I needed a way of generating all possible anagrams of a word. After a while and several not-so-cool solutions, I walked into a good implementation in a forum, changed it a bit, and there you go, an anagram-generator (using enchant).
#this needs pyenchant and itertools. Generates all 'correct' anagrams - i.e. that pass the enchant spelling check.
def anagram_list(word):
     from itertools import permutations
     import enchant
     d = enchant.Dict('en_GB')
     return [''.join(w) for w in permutations(word, len(word)) if d.check(''.join(w))== True]

Polygons and other geometric needs

For another project, I needed to generate shapes with the same area, and save them to a .svg file. I found out a bunch of very useful libraries for doing geometric things. Library Polygon helps creating and managing polygons of n sides; svgfig helps generating SVGs.

Some code I patched together for computing the area of any polygon (general formula from wikipedia).

#suppose you have a polygon as a list of 2-element tuples, each of which is a point in a 2d-space.
#your n-vertex polygon looks like [(x0,y0),(x1,y1),...,(xn,yn)]
def area(p):
    return 0.5 * abs(sum(x0*y1 - x1*y0 for ((x0, y0), (x1, y1)) in segments(p)))

def segments(p):
    return zip(p, p[1:] + [p[0]])

Then I needed to check whether the polygons I randomly generated were convex or not. For this, I found this very nice idea from Bastian Molkenthin, complete with Java code for it. Bastian defines a function of three vertexes, that has value zero if the third point lies on the line defined by the first two, and has positive value on one side of it and negative on the other. Moving along the polygon vertexes, the function has to keep its sign constant for the polygon to be convex. My python implementation of his algorithm could be nicer, but it works.

#this checks the sign of a number
 def sign(x):
    if x >= 0: return 1
    else: return 0
#this defines triples of subsequent vertexes on any polygon
 def triads(p):
    return zip(p, p[1:]+[p[0]], p[2:]+[p[0]]+[p[1]])
#this uss Bastian's three-vertex function to check convexity
 def check_convexity(p):
    i = 0
    for ((x0, y0), (x1, y1), (x2,y2)) in triads(p):
        if i==0: fsign = sign(x2*(y1-y0)-y2*(x1-x0)+(x1-x0)*y0-(y1-y0)*x0)
            newsign = sign(x2*(y1-y0)-y2*(x1-x0)+(x1-x0)*y0-(y1-y0)*x0)
            if newsign != fsign: return False
        i +=1
    return True

One thought on “Python code

  1. Hi! Thanks a lot! You’re code snippet for the polygons was very helpful. I’d like to suggest summing up the values in check_convexity just to be sure the path doesn’t do more than one round before closing up. You never know…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s