On 4/9/2012 11:57 AM Kiuhnm said...
Do you have some real or realistic

... yes

(but easy and self-contained)

.... aah, no.

examples when you had to define a (multi-statement) function and pass it
to another function?

This weekend I added functionality to a subsystem that allows users to write simple get functions stored in [funcname].py files in a specified directory that are read, compliled, and stored in a dictionary to be executed dynamically. So, when a properly crafted command is recieved the corresponding function object is retrieved from the dictionary and exectued.

... hang on ...  ok -- here's a simple self contained example - HTH!

Emile

----

STACK=[]

def push(this):
    STACK.append(int(this))

def plus(this):
    tosa,tosb = STACK.pop(),STACK.pop()
    push(tosa+tosb)

def minus(this):
    tosa,tosb = STACK.pop(),STACK.pop()
    push(tosa-tosb)

def times(this):
    tosa,tosb = STACK.pop(),STACK.pop()
    push(tosa*tosb)

def div(this):
    tosa,tosb = STACK.pop(),STACK.pop()
    push(tosb/tosa)

def equals(this):
    return STACK.pop()

funcs = { "+" : plus,
          "-" : minus,
          "*" : times,
          "/" : div,
          "=" : equals
          }


def calculate (text):
    for part in text.split():
        retval = funcs.get(part,push)(part)
    return retval


assert calculate ("4 3 + =") == 7
assert calculate ("4 3 * =") == 12
assert calculate ("12 3 / =") == 4
assert calculate ("1 2 3 4 + + + =") == 10

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to