This question already has answers here:
Why does my recursive function return None?
(4 answers)
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 2 years ago.
Below code returns "None"
But, when I change (return sum) to (return
print(sum)) it returns right value.
Why does this problem occur?
def good(num,sum):
if num == 0:
return sum
sum = sum + num
num = num - 1
good(num,sum)
sum = 0
a = 3
k = good(a,sum)
print(k)
The return statement is missing!
Do this:
def good(num,sum):
if num == 0:
return sum
sum = sum + num
num = num - 1
return good(num, sum)
This is because the function is called but is not returning the new values recursively.
One of the best website that explains this in depth and clearly is realpython.com, have a look especially at: maintaining-state but I suggest you to have a look at the whole article.
For sake of completeness I quote a section where I think is related to the issue you encountered:
Behind the scenes, each recursive call adds a stack frame (containing its execution context) to the call stack until we reach the base case. Then, the stack begins to unwind as each call returns its results.
unwind: Basically it returns it backward.
When dealing with recursive functions, keep in mind that each recursive call has its own execution context.
Other Stack Overflow Related questions
recursive-function-returning-none-in-python
python-recursion-with-list-returns-none
i-expect-true-but-get-none
Related
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 months ago.
Nothing is returned when I try iterating a function in Python.
Code is like this
def count(num):
if (num > 10):
return(num)
if(num<=10):
new = num + 1
count(new)
nummer = count(8)
If I do count(22), it returns 22. But when I do count(8), it doesnt return anything. I would like this function to return '11' but it return nothing.
Probably something wrong in my thinking but I really can't figure it out.
I hope someone can help me.
Thx,
Peter
Your second recursive call lacks a return statement, so that branch will always return None. You will need to explicitly return the result of count there, i.e.
return count(new)
You actually need to include a second return, in case your number is lower or equal than 10. Besides, you could have a slightly shorter code. Calling the function is not sufficient.
You are trying to evaluated whether a number x is greater or lower than 10. But this number can EITHER be greater OR lower. Therefore when you put
if num>10:
pass
you don't need another if statement, since if num is not greater than 10 it is lower or equal to 10.
def count(num):
if (num > 10):
return(num)
else:
new = num + 1
return count(new)
nummer = count(8)
you cannot return the value in other conditions. Try this
def count(num):
if (num > 10):
return(num)
if(num<=10):
new = num + 1
return count(new)
nummer = count(8)
This question already has answers here:
Python recursive function returning none after completion
(3 answers)
Closed 1 year ago.
I'm programming the josephus algorithm.
The Josephus Problem is a mathematical problem in which a circle is made, its circumference formed of n people.
Starting from the person in the 0th position, each person eliminates the person to their left (the next person in the circle). The next living person then does the same, and the process is repeated until there is only one person left alive.
I used a recursive function like this :
def loopInList(L):
if len(L)>1:
i=0
while i < len(L) - 1 :
L.remove(L[i+1])
i += 1
loopInList(L[i:] + L[:i])
else:
return L[0]
def josephus(n):
L = [x for x in range(n)]
return loopInList(L)
print(josephus(9))
The problem is that it's returning me None, yet when I print L[0] instead of returning it, I have this list [2,0] which is the good result, so my algorithm works. But it only return the value of the first function loopInList called (the one that get the fresh list as argument), and with this fresh list I don't go in the else statement so it's returning None. I want my first function called to return the value returned in the last function called in the recursive loop.
Did you intend this (just added the return statement in the recursing block):
def loopInList(L):
if len(L)>1:
i=0
while i < len(L) - 1 :
L.remove(L[i+1])
i += 1
return loopInList(L[i:] + L[:i])
else:
return L[0]
def josephus(n):
L = [x for x in range(n)]
return loopInList(L)
print(josephus(9))
This question already has an answer here:
Why Python recursive function returns None [duplicate]
(1 answer)
Closed 2 years ago.
I am trying to write a code to calculate GCD of two numbers(n and m) recursively. I want my answer to update in gcd_val as the recursion progresses. I tried debugging and can't understand why it chooses the earlier gcd_val as compared to the value obtained in its sub-call(inner recursive call). I want to know why is this happening and what should be the correct way to do it? I get the answer 2 when it should be 4.
def find_gcd(n, m, gcd_val):
factor_list = [2, 3, 5]
if n == 0 or m == 0:
return 0
for f in factor_list:
if n % f == 0 and m % f == 0:
find_gcd(int(n/f), int(m/f), gcd_val)
gcd_val *= f
return gcd_val
print(find_gcd(20, 8, 1))
Almost all programming languages defaults to pass arguments by value. That is the second the function starts up the arguments are unique memory locations for just that round and all alterations done with it will never affect a prevous call even if it is the same name.
Programming languages doesn't discriminate between self calling or caling something else so when find_gcd calls find_gcd it treats it the same as if it called find_gcd2 with a similar implementation.
Just like you use print you actually need to use the returned value or else the recursive call in find_gcd is dead code.
This question already has answers here:
check for duplicates in a python list
(7 answers)
Closed 4 years ago.
I am a TOTAL Noob so please be gentle!
I have written this code:
def sorted_has_duplicate(numbers):
numbers.sort()
duplicate = False
for num in range(len(numbers)-1):
if numbers[num] == numbers[num + 1]:
duplicate = True
break
return duplicate
The code runs fine and it does what it is supposed to do which is find the first duplicate value in a list if any and return True or False.
My question is how can I have the same function perform the same task if the list is not sorted (sorting is not allowed) and i can only use built in python functions?
Collect nums in a set as you iterate:
def has_duplicate(numbers):
seen = set()
for num in numbers:
if num in seen:
return True
seen.add(num)
return False
You can also shorten this down to:
def has_duplicate(numbers):
return len(numbers) != len(set(numbers))
This simply checks whether the list has as many elements as its set which by definition has no duplicates.
Note that both these set-based solutions run in linear time because of a set's O(1) contains-check. The naive brute force approach of searching for each element in the list remainder
def has_duplicate(numbers):
for i, num in enumerate(numbers):
if num in numbers[i+1:]:
return True
return False
is quadratic because of a list's O(N) contains-check.
This question already has answers here:
Python Script returns unintended "None" after execution of a function [duplicate]
(3 answers)
Closed 6 years ago.
This is a function that is able to take in a binary number as a string and convert it into a decimal number. For some reason, this function always returns None and I can not understand why this is happening. If anyone could provide me with an explanation it would be much appreciated.
total = 0
power = 0
def binaryToDecimal(binaryString):
global total, power
n = len(binaryString) - 1
if n < 0:
return total
else:
if binaryString[n] == '1':
total += (2 ** power)
power += 1
binaryToDecimal(binaryString[:-1])
The final line needs to be return binaryToDecimal(binaryString[:-1]). At the moment you're returning total from the last call, but none of the preceding calls are returning anything.
Instead of recursive call for that, just a for loop like below should do
def binaryToDecimal(binaryString):
total=0
# strip of 0b if there is any
binaryString = binaryString.lstrip('0b')
n=len(binaryString)
for i in range(n):
# index from lsb bit to msb
if binaryString[n-1-i] == '1':
total += (2 ** i)
return total
Alternatively, its recommended to just use python built in int function
def binaryToDecimal(binaryString):
return int(binaryString, 2)