k b
k b

Reputation: 9

Reduce if-else loops

Is there any way to reduce the following function?

def treefix(p):
    if p.parent:
        if p.parent.size==1:
            treefix(p.parent)
        else:
            p.children=[]
            sizefix(p)
    else:
        p.children=[]
        sizefix(p)

I tried the following but it didn't work the same way.

def treefix(p):
    if p.parent:
        if p.parent.size==1:
            treefix(p.parent)
    p.children=[]
    sizefix(p)

Upvotes: 0

Views: 102

Answers (3)

alani
alani

Reputation: 13079

As another answer points out, the simplification you need is just:

def treefix(p):
    if p.parent and p.parent.size == 1:
        treefix(p.parent)
    else:
        p.children=[]
        sizefix(p)

The code in the question will avoid evaluating p.parent.size==1 in the event that p.parent has a value that yields False. This may be important, because for example if p.parent has the value None, then trying to evaluate p.parent.size would raise an AttributeError.

However, despite possible appearances, the same also is true with the simplified and expression shown here, because of short-circuit evaluation.

Specifically, the second operand (i.e. after the and) will be evaluated only if the first operand (i.e. before the and) yields True. If the first operand yields False, then the whole and expression will evaluate to the value of the first operand without the right-hand operand ever being evaluated.

Only if the first operand yields True, the result of the and operation will be the value of the second operand.

So the ordering here is important, and it would not work to write:

    if p.parent.size == 1 and p.parent:

Upvotes: 1

ksohan
ksohan

Reputation: 1203

You can use return

def treefix(p):
    if p.parent:
        if p.parent.size==1:
            treefix(p.parent)
            return
    p.children=[]
    sizefix(p)

Upvotes: 0

deadshot
deadshot

Reputation: 9071

Try this:

def treefix(p):
    if p.parent and p.parent.size == 1:
        treefix(p.parent)
    else:
        p.children=[]
        sizefix(p)

Upvotes: 2

Related Questions