lists of functions

2009 June 20
by pythonisms

This little gem of code uses two facts that I have just discovered, first that since a function is an object, that you can put several functions in a list, and access each of them one by one iteratively, the second is that if a = True and b = True, that a+b in fact equals 2, which seems to have been included in python in order to allow some very useful shortcuts. We are looking for palindromic primes ( a nice simple example), so we need a prime test function and a palindrome test function, as:

def a(x):
    if str(x)==str(x)[::-1]:
        return True
    else:
        return False

def b(x):
    for z in range(2,x**0.5):
        if x%z==0:
            return False
    return True

then we just stick the functions in a list and iterate over it, returning positive if every case is true, so:

for xx in range(1000):
    cc=0
    for zz in [a,b]:
        cc+=zz(xx)
    if cc==2:
        print (xx)

just another way to do it, but the concept that a function can be treated like any other entity is critical. It’s as if floats, ints, strings and functions are all just these structures that can be referred to in any other code. It’s as if…

they are just objects

objects to be manipulated, objects to be stored, objects to be referred to. And that word is key, because in fact any of those structures is like a physical object that you can do things with, hence we call this new concept “Object Oriented Programming“, since it is based around them !!

we’ve gone far today.

No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS