Why does this recursive addition return none - python-3.x

This is a weird one print return 9 and then it prints 1 , also i checked debugger in pycharm and the (stuff) keeps counting down for some reason
def repeater(stuff):
if stuff != 9:
stuff += 1
print(stuff)
repeater(stuff)
return stuff
print(repeater(0))

When you call repeater(stuff), you're not passing the variable stuff, you're passing a copy of the variable stuff. When you say stuff += 1, you're not modifying the stuff you called the function with, you're modifying a copy of it. That change isn't reflected in the original when you exit the function.
Then, when the function exits, you don't do anything with the returned value of stuff - which is, again, copied out of the function in reverse. Python does let you call the function without using its return value, but it looks like your intent here is to apply the returned value of repeater(stuff) to stuff.
To accomplish that, simply change the line
repeater(stuff)
to
stuff = repeater(stuff)

The reason for that additional 1 that is coming in the end is that repeater(stuff) is returning the value of stuff which is being received by your print statement i.e. print(repeater(0)). When all the recursive calls return back, none of the values are stored/used but the very first call that was made by print(repeater(0)) obtains a value of 1 because repeater(stuff) returns the value of stuff which would be 1 after stuff += 1 during the first call.
You can read more about how recursion works for more clarity.

Related

Why is this Binary search returning as NoneL

I made this recursive binary search algorithm which cuts the list in half every time and I don't understand why it is returning null.
def recursionSearch(target, numlist):
if len(numlist) == 0:
return -1
mid = len(numlist)//2
if numlist[mid] == target:
return mid
elif(target < numlist[mid]):
recursionSearch(target,numlist[:mid])
else:
recursionSearch(target, numlist[mid+1:])
Supposed to return index of the target
You forgot to add return to your recursive calls:
return recursionSearch(target,numlist[:mid])
Without those you're executing the search but discarding the results.
Just as a tip, you should debug things like this by exploring what your program flow is like. If you don't want to use an actual debugger, you can just insert print statements at relevant program points to learn what's getting run and with what values.

Is it possible to set the result value of 'None < None' to False in python?

I want to get that result when I write only None < None in the editor without using try, except. Of course, I tried to redefine the __lt__ function of None, but an error occurred. Is there any good way?
hi and thanks for answering. I know it's odd to compare 'None' and 'None'. Nevertheless, a result value (True or False) is required.
Take a look at the example code below
if func1() < func2():
~~~~
In this case, if either func1() or func2() has None, you can add code that handles whether one of them is None.
if func1() and func2():
if func1() < func2():
~~~~
However, it is very cumbersome to add these conditional statements one by one every time a comparison statement is encountered in the code I am working on (at least 1 million lines exceed).
So, if there is even one None in the comparison statement, I want to get the result value (If None is compared, it is treated as False) so that the code inside the if is not executed.
And as mechanical_meat said 'lt' means __lt__()

how to use variable from function

def message(number):
`number+=2`
print(number)
ans = message(number)
return number`
if ans == 3:
`print("theory was right")`
number=1234
message(1)
print(number)
In the above code, I am not able to use variable returned from def() out of the function body. Is there a way I can do it? Pls. don't mind indents coz this is my first post here. thnx
I've tried
ans = number
also
ans = message()
but still not able to do get the output
Firstly, you build an infinite recursion - if you want to use a function inside itself, you have to insert a condition which will stop the recursion and let you get a result.
So, above ans = message(number), you should place if statement.
Secondly, you cannot use a variable out of a function, if it is not returned - it has never been counted.
You probably got confused it with possibilty of using global variables out of loops.
To sum up, if you want to check ans, you have to return it in a function and call the function like this (it is not the solution):
def function(x):
ans = message(number)
return ans
if funcion(x):
print("theory was right")

The function has been called 10 times but the decorator has only been called once. Why?

def call_counter(func):
print('Called\n')
def helper(x):
helper.calls+=1
return func(x)
helper.calls=0
return helper
#call_counter
def succ(x):
return x+1
print(str(succ.calls)+'\n')
for i in range(10):
print(succ.calls)
succ(i)
print('\n')
print(succ.calls)
You commented:
I don't understand why the decorator is called on the function only once. It should be called 10 times, right? One time for every iteration in the loop and therefore 'Called' should be printed 10 times. What am I missing?
I think you are confusing runs of the decorator for runs of the wrapper function (named helper in your code). The decorator is only called once, when it gets passed the original function and returns the wrapper function, which is what gets stored as succ in your module. The wrapper is what gets called ten times by your loop.
When I run your code, this is the output I get:
Called
0
0
1
2
3
4
5
6
7
8
9
10
Only the first two lines ("Called" and the empty line after it) come from the decorator call. You can see this if you run only the function definition, and not the loop. You'll see "Called" printed out immediately, even if you never call the function at all.
The zero at the top and the ten at the bottom are from the print statements you have at the top level. The numbers printed close together are the output of the loop, which prints the count of previous calls just before it makes each new call to the wrapped function.

Is this recursive?

Second attempt here, I just wanted to know if this is considered a recursive function.
The purpose of the function is to take a string and
if the the first element is equal to the last element
then append the last element to a list and return nothing,
else call istelf and pass the same string from index [1]
finally append the first element to the list
I know that error checking needs to be done on the if statement. However I am only doing this to try and get my head around recursion...Struggling to be honest.
Also I would never write a program like this if it where anything but trivial I just wanted to check if my understanding is correct so far.
def parse(theList):
theList.reverse()
parsedString = ''.join(theList)
return parsedString
def recursiveMessage(theString):
lastElement = theString[len(theString) - 1]
if theString[0] == lastElement:
buildString.append(theString[0])
return None
else:
recursiveMessage(theString[1::])
buildString.append(theString[0])
toPrint = "Hello Everyone!"
buildString = []
recursiveMessage(toPrint)
print(parse(buildString))
Thanks again.
Is this recursive?
If at any point in a function's execution it calls itself, then it is consider recursive. This happens in your example, so recursiveMessage is indeed recursive.
so which is quicker recursion or iteration?
Recursion is usually much slower and consumes more space due to a new stack frame having to be created on the call stack each recursive call. If you know your recursive function will need to be run many times, iteration is the best route.
As an interesting side note, many compilers actually optimize a recursive function by rolling it out into a loop anyways.

Resources