Pixar's color scripts

Visualizing The Incredibles' color script.

The Duck Tale

The one about hand-making Korean wedding ducks.

Smile

Transforming sketches into a mixed media piece.

The mixed media process

A photo narrative about making a mixed media piece.


Simple predicates using lambdas in Python

Posted on 2007-12-04 07:04:47

I have been spinning in Python for a few days now in an attempt to port some C# bits. In the C# codebase, I typically exercised the following:

List list = new List();
list.Add(PreviouslyInstantiatedType); // Imagine many populators
list.FindIndex(delegate(T) { T.someProperty == true; });

I love being able to pass in anonymous functions or function pointers around. Imagine building up a tree of nodes and returning the position in the tree where a given node's property has a specific value or a combination of values. Of course, the beauty of this relies on the underlying looping - boring stuff to constantly copy/paste throughout your code.

So as I was writing the equivalent Python, I came up with:

list = []
list.append(PreviouslyInstantiatedType)
list.index(lambda x: x.someProperty == True)

Everything looks cool - right? Well, that doesn't seem to work. It turns out that index does not seem to like functions/lambdas as evaluators.

Here is a first stab at implementing something for this. Note, I am just trying to cheaply clone C#'s list method "FindIndex" and have not checked out Python's list method "index."

def fIndex(f, list):
    for i in xrange(len(list)):
        if f(list[i]):
            return i
    return -1

This iterates through the provided list, and applies the function for every item. In this case, there should be some sort of type checking that the function is a boolean - rather than error catching.

In putting all of this together, imagine the following object and list:

class person:
    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName

people = [person('j','h'),person('k','a'),person('n','g')]

Now, let's print out the first position in the list where the person's last name is 'a', I would do:

print fIndex(lambda p: p.lastName == 'a', people)

This whole thing is extremely low-fi - but I am digging it.

Categories

Art
ColdFusion
Data Visualizations
Design
Inspiration
JavaScript
Life
Python
Ruby
Snippets

Elsewhere

Facebook
Gravity
Twitter

Subscribe to this blog


Content by Kunal Anand. Connect with me on Twitter, Facebook, or email.