My brother thinks he’s a chicken

“… I thought of that old joke, y’know, the, this… this guy goes to a psychiatrist and says, “Doc, uh, my brother’s crazy; he thinks he’s a chicken.” And, uh, the doctor says, “Well, why don’t you turn him in?” The guy says, “I would, but I need the eggs…”

Annie Hall (1977) by Woddy Allen

I have been thinking allot recently about some significant decisions I have to make regarding my career, many times I found myself summarizing: I would, but I need the salary… ♥

Advertisements

Python Safe Calculator

Web-Safe Arithmetic Expressions Evaluator

import math
import re

whitelist = '|'.join(
    # oprators, digits
    ['-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '\d+']
    # functions of math module (ex. __xxx__)
    + [f for f in dir(math) if f[:2] != '__'])

valid = lambda exp: re.match(whitelist, exp)

>>> valid('23**2')
<_sre.SRE_Match object at 0xb78ac218>
>>> valid('sys.exit(100)') == None
True
>>> exp = '23**2'
>>> if valid(exp):
>>>     x = eval(exp)

came across this post via unofficial planet python


Startup Entrepreneur?

First they ignore you.
Then they laugh at you.
Then they fight you.
Then you win.

MK Gandhi


Fibonacci, Generators and Python

Python is so beautiful and elegant

See this:

def fib():
    a, b = 0, 1
    while 1:
        yield b
        a, b = b, a+b

if __name__ == '__main__':
    f = fib()
    for i in xrange(1000):
        print f.next()

from: http://www.python.org/dev/peps/pep-0255/


Accumulator Generator

I just came across this PG’s page:

Accumulator Generator

Revenge of the Nerds yielded a collection of canonical solutions to the same problem in a number of languages.

The problem: Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i.

Note: (a) that’s number, not integer, (b) that’s incremented by, not plus.

For python he offers this approach:

class foo:
    def __init__(self, n):
        self.n = n

    def __call__(self, i):
        self.n += i
        return self.n

I thought of it for a few seconds and realized that this class instantiation is not necessary. Same can be achieved this way:

def foo(n):
    def _inci(n, x):
        n+=x
        return n

    return lambda i: _inci (n,i)

Googlereader, Heaven’t you heard of firebug?

… and I thought this method of raising errors belongs to the far past of web development…

google-debugging.png