This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 4 years ago.
I had trouble understanding why this function returns None:
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
if x == a:
return 0
elif x < a:
return x
else:
rem(x-a, a)
rem(7, 5)
I then realized that the last line in the function should be:
return rem(x-a, a)
I am still unsure as to what really happens in the first one. It looks like there are 2 seperate function calls, one returning 2 and the other None... any help?
All python function returns None if it doesn't terminate by a return statement. In your case, you successfully called the recursion but you discarded the result in the else part. And after the if-block, the default return None is implicitly executed.
Related
This question already has answers here:
Is the shortcircuit behaviour of Python's any/all explicit? [duplicate]
(4 answers)
Closed 9 months ago.
Will python's all function exit as soon as it finds a False in the iterable? Or will it continue checking the rest?
For example, if i is not divisible by 20, will the below code continue checking if it is divisible by 19 and 18 and so on?
def min_divisible(target_n):
'''
Returns the smallest number that is divisible by all integers between 1 and n
'''
i = target_n
while not all((i%j == 0) for j in range(target_n,2,-1)):
i+=target_n
return f'{i:,}'
print(min_divisible(20))
all will stop the iteration as soon as it encounters a "falsey" object. You can see this with a simple example:
def produce_numbers():
for k in range(10):
yield k
print(k)
all(k < 3 for k in produce_numbers())
This prints
0
1
2
This is spelled out in Python's documentation. It states that the following is a functionally equivalent definition of all:
def all(iterable):
for element in iterable:
if not element:
return False
return True
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 1 year ago.
could someone please indicate to me what's wrong with the logic of the simple recursive function, below:
def palindrome (string):
if len(string)<=1:
return True
elif string[0]== string[-1]:
palindrome(string[1:-1])
else:
return False
the False part, works ok, for example :
palindrome('good') the function returns correctly False.
but if it's fed a palindrome like :
palindrome('level') the function returns nothing.
As mentioned in the comments, you don't return the function when calling it recursively, but you should, or the original function call will return None.
Solution:
def palindrome (string):
if len(string)<=1:
return True
elif string[0].lower() == string[-1].lower():
return palindrome(string[1:-1])
else:
return False
I would also add "lower" as capitalization isn't relevant
This question already has an answer here:
Why Python recursive function returns None [duplicate]
(1 answer)
Closed 2 years ago.
I'm trying to create a recursive function in Python (as part of an online course) which takes two numbers and returns the highest common denominator between them, however, the function won't return the value.
My code is:
def gcdRecur(a, b):
x = min(a,b)
y = max(a, b)
if x == 0:
return y
else:
gcdRecur(x, y%x)
When I test the function with
gcdRecur(2,12)
or
gcdRecur(6,12)
nothing is returned. I know the function works because if I print y before I return it then the correct denominator is printed to the console, I'm just not sure why the function doesn't output y.
It's probably something obvious but as I'm new to Python I'm not sure what I'm doing wrong.
Any help would be much appreciated.
You need to return something in both branches:
else:
return gcdRecur(x, y%x)
This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 4 months ago.
I came across following code while solving this problem:
f=lambda n:"a"[n:]or f(n-1)+chr(97+n)+f(n-1)
The function generates abacaba sequence of specific depth n
For example:
n = 2, output: 'abacaba'
n = 3, output: 'abacabadabacaba'
The question is, how does the code work? Namely, how does "or" operator work inside lambda? (I assume code above uses recursion, and to my knowledge, normally we use loops for recursion, but I don't see anything that resembles loops in the code above)
It works the same way it does anywhere else. If the left-hand argument of or is truthy, the expression evaluates to that; otherwise, it evaluates to the right-hand argument. In this case, "a"[n:] is the empty string when n > 0, so it's equivalent to
def f(n):
if n == 0:
return "a"
else:
return f(n-1) + chr(97+n) + f(n-1)
Let's break it down.
f = lambda # declare a variable f that is a function
n: # that takes an int parameter 'n'
"a"[n:] # if n is 0 return 'a'
or # else
f(n-1) # return a recursive call at n - 1
+ # plus
chr(97+n) # character from code 97 + n
+ # plus
f(n-1) # another recursive call
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 years ago.
I made a simple function to identify the tennis player who served the last point in a tie-breaker match. Below is my code, which returns the player but when I am printing the result, I get None.
def get_tie_break_point_server(s,tie_break_sum,playerA,playerB):
s = s+1
if(s == tie_break_sum):
return playerB
s = s+1
if(s == tie_break_sum):
return playerB
else :
get_tie_break_point_server(s,tie_break_sum,playerB,playerA)
tie_break_score = [2, 2]
playerA = "A"
playerB = "B"
tie_break_sum = tie_break_score[0] + tie_break_score[1]
print get_tie_break_point_server(1,tie_break_sum,playerA,playerB)
Your function returns None when it reaches the last 'else' block. When a function reaches the end of its code block without an explicit return statement it will implicitly return None. You need to change the last line to
return get_tie_break_point_server(s,tie_break_sum,playerB,playerA)