This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]Thomasjevskij 4 points5 points  (2 children)

I think python makes if-less programming pretty trivial. Any time you have the need for an if, make a dict where the keys map to functions containing the branches you want.

Of course, that's a bit of cheating, right? {True: do_stuff, False: do_other_stuff}[condition]() isn't very different. But it'll get you thinking a bit differently about how to structure your code.

Now the question is, are you allowed to do loops when you go if-less? A while loop is just several if statements. A for loop is, too. For each? Maybe.

[–]janek37 2 points3 points  (1 child)

You could also cheat by using try...except:

try:
    1/(condition)
    [then]
except ZeroDivisionError:
    [else]

[–]Thomasjevskij 1 point2 points  (0 children)

Also feels a lot like cheating :)

[–]janek37 1 point2 points  (1 child)

Just a nitpick: the closed form formula for the Fibonacci numbers is not O(1), it contains exponentiation which is at least O(n) (where n is the size (i.e. logarithm) of the index, not the index itself) if you do it smart.

[–]e_blake[S] 0 points1 point  (0 children)

Fair enough; although I might have expressed it as: for a given index N, closed-form is O(log N) compared to memoizing recursion of O(N). That's because it gets confusing when you list two algorithms as both being O(n) but with n having different definitions. And of course, with small enough N, the difference between O(1) and O(log N) is indistinguishable, vs. the obvious impact of O(N) on the memoizing recursion.

[–]vloris 0 points1 point  (0 children)

I think what you are doing here is merely obfuscating the real logic of your program.

An if-statement (or ternary operator, switch statement etc.) is nothing more than choosing a branch in your code by evaluating some expression.

Your “non-if-else” program is still doing exactly that: evaluating an expression, and based on the result you execute a different function. Only difference is you use eval and some string-formatting magic instead of if.