Python IF THEN chain equivalence

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Nov 14 09:27:38 EST 2008


On Fri, 14 Nov 2008 01:24:32 +0100, M.-A. Lemburg wrote:

>> Apparently you haven't seen
>> any Forth, assembly, et al code. All you're doing is having the branch
>> point for each conditional be the end of the chain, otherwise it falls
>> through to the code after the conditional.  This is done all the time
>> in languages that let you actually manipulate the hardware.
>>
>> Just as a suggestion   a little humility would go a long way toward
>> being open minded and receptive to different paradigms.
> 
> Without giving any hint as to what the quoted snippet of code is written
> in, how do you expect people to make any sense of it ? Especially when
> using an RPN stack oriented language in a Python forum.
> 
> There's a reason why we hide Python byte code running on the VM stack
> machine from Python users ;-)

It's not like Forth is precisely an obscure little language. For a time, 
it was possibly more popular than C. Or predated C? Whatever. I know I 
learned about Forth long before I had even heard of C.

Other RPN languages include Postscript, not exactly unheard of either. 
Open Firmware is Forth-like, and as you point out yourself, Python byte 
code also is a stack-based language.

In conclusion, I'm not sure which is more disappointing: that the OP 
couldn't be bothered to mention he was using a Forth-like syntax, or that 
so many people failed to recognize it.

Anyway, for what it's worth, here's my translation into Python.

if  x1 < limit:
    a()
    if  x2 < limit:
        b()
        if x3 < limit:
            c()
            # blah blah blah...
                                    if x10 < limt:
                                        j()


Not very nice code. I think a better way is something like this:

keys = [x1, x2, x3, x4, x5, x6, x7, x8, x9, x10]
functions = [a, b, c, d, e, f, g, h, i, j]

for key, function in zip(keys, functions):
    if key < limit:
        function()
    else:
        break



-- 
Steven



More information about the Python-list mailing list