Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need both condition branches for the rreverse function?

I had an exercise and tried to use parts of code I found here on another person's question, but I found that I needed a part of code that I have no idea why I do.

The full code I was using for my function is this:

def rreverse(s):
    if s == "":
        return s
    else:
        return rreverse(s[1:]) + s[0]

But I only used the else as a statement, and I didn't get the result I was hoping for.

def recur_reverse(x):
    if x != "":
        return recur_reverse(x[1:]) + x[0]

I got TypeError saying "unsupported operand type(s) for +: 'NoneType' and 'str'."

What is the logic behind this first example working fine and the second one throwing an error when the difference is this if statement? and why is my version incorrect?

Thank you!

like image 780
Hilla Shahrabani Avatar asked Sep 25 '18 11:09

Hilla Shahrabani


People also ask

Why do we use conditional branching?

They allow result of signed and unsigned data operations, or compare operations to be used for branch control. For example, if we need to carry out a conditional branch after a compare operation “CMP R0, R1”, we can use one of the following conditional branch instructions in Table 6.3.

What is the effect of conditional branch?

A conditional branch instruction branches to a new address only if a certain condition is true. Usually the condition is about the values in two registers.

Why is branching bad for performance?

On a conditional branch, it usually doesn't know ahead of time which path will be taken. So when this happens, the CPU has to stall until the decision has been resolved, and throws away everything in the pipeline that's behind the branch instruction. This lowers utilisation, and therefore performance.

What is an example of conditional branching?

In this example, there are only two branches. The first branch, which selects a loan offer from United Loan, is executed if a case condition containing an XPath Boolean expression is met. Otherwise, the second branch, which selects the Star Loan loan offer, is executed.


1 Answers

the problem with the second construct is that if s is the empty string, the function returns None which isn't a string, and the end-caller expects a string, even empty, so returning None will make the caller code break (which leads to questions like Why does my function return None?)

You could write it with a ternary expression to make sure that it returns something whatever the value of x

def recur_reverse(x):
    return recur_reverse(x[1:]) + x[0] if x else ""
like image 183
Jean-François Fabre Avatar answered Sep 28 '22 05:09

Jean-François Fabre