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!
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.
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.
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.
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.
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 ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With