Can someone please explain to me how this piece of recursive code is working? Because there is only one if statement which checks if variable x is equal to zero and returns true if the value is equal to zero.
And the other part is just upon calling each other.
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_odd(17)) # outputs true
print(is_even(23)) # outputs false
This pair of mutually recursive functions makes use of three facts:
0 is even
x is even if x - 1 is odd.
x is odd if x - 1 is even.
1 is odd because 1 - 1 == 0 is even.
2 is even because 2 - 1 == 1 is odd.
And so on.
This is not an efficient way to determine if an arbitrary value n is even or odd, but it is a logically correct way. (Assuming the argument is always a natural number, anyway. Passing a negative integer as an argument to either results in infinite recursion, as the base case will never be reached.)
I want to give a simpler answer to follow along with. Think about the stack trace. I'll abbreviate is_even and is_odd as IE and IO respectively.
IO(17)
NOT[IE(17)]
NOT[IO(16)]
NOT[NOT[IE(16)] = IE[16]
IO(15)
...
This is basically checking if alternating descending numbers starting from the input value are even and odd all the way down to 0. Note that if we start with a true statement (like IO(17)) then every line contains a true statement - if we started with a false statement, every line ends up with a false statement. Following the pattern we see here, we see that the final state can therefore end up as
IE(1) -> IO(0) -> NOT[IE(0)] = NOT[True] = False # as expected!
OR
IO(1) -> NOT[IE[1]] = NOT[IO[0]] = NOT[NOT[IE(0)] = NOT[NOT[True]] = True # likewise!
Related
Code
def addition(num):
if num:
return num + addition(num - 1)
else:
return 0
res = addition(10)
print(res)
Explanation
I know what the function is doing:
it is a recursive function
I just don't know what if num: means or the else part.
I am guessing it means as long as the num is int do what is inside the if, else return 0.
Question
Can someone tell me what this code means?
if variable: and truthyiness
See the boolean values and Python's Truth Value Testing:
What is Truthy and Falsy? How is it different from True and False?
You can evaluate truthy and falsy values using the bool() conversion-function:
print('None:', bool(None))
print('zero:', bool(0))
print('negative:', bool(-1))
print('positive:', bool(1))
if num: mets if num is defined and unequal to 0:
is defined: num is not None
and is not zero: num != 0
bool(0) is False. The opposite condition is tested by if not num.
The role of if in a recursive function
It's a recursive function which calls itself until exit-condition num == 0 is met in the else branch. Then it simply returns 0. So, the role of if num: is the continue-condition opposed to an exit-condition.
You could also write it as exit-condition:
def addition(num):
if not num: # equivalent to: if num == 0 or num is None
return 0 # return 0 if exit-condition met
# default behavior: recurse until zero met
return num + addition(num - 1)
See also:
recursive factorial function
Basics of recursion in Python
Edge-cases for input
Note, how input of None and other falsy values return a zero.
Please also consider the edge-case of negative input, as Fred commented. Could (silently) return 0 to abort addition. Also might raise an error to warn about misuse, like:
if num < 0:
raise ValueError("Can not calculate the recursive-sum for negative values.")
What happens if a float like 10.5 is given as input?
It would step through each -1 decrease until 0.5. The next call of addition(-0.5) would jump over the num == 0 exit-condition and cause infinite recursion, even a stackoverflow.
Python and many other languages have a concept of "falsy", which roughly means "values that are treated as False when evaluated as a boolean". In Python, values that are falsy include empty collections such as empty lists, strings, sets, tuples, and dicts, the int or float 0, and None. I may be missing some here, and you may find that some classes are designed to be treated as falsy as well under certain conditions. There are also "truthy" values which evaluate to True is a boolean context. It's easy to find out if a value is truthy or falsy. Simply call bool() on it:
bool(0.0)
# False
In the context of your code, when 0 is reached, that will be evaluated as falsy, triggering the exit condition.
if num: means if num is different than 0 : if num!=0.
you better remove the else statement.
def addition(num): if num: return num + addition(num - 1) return 0
python already knows that return is an else statement.
here's a playlist of one of the bests on youtube by corey to learn & become at python : https://www.youtube.com/watch?v=YYXdXT2l-Gg&list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7
and also I recommend this book, automating the boring stuff with python. it's free : https://automatetheboringstuff.com/
def greater(list, num)
for x in list:
if x > num:
return True
else:
return False
as you can see in my code, i am trying to write a function that return True if list_number contained number that is bigger than second argument, otherwise return False.
but here is confusing:
when i input: greater([1, 2, 3], 2), and its return False. I am wondering why is that? the first argument contained 3 and its bigger than 2.
any helps and explanations will be appreciated.
You want to have it return at the end of the function. Right now, you have it return after checking only the first number. Try this:
def has_gt(list_number,number):
for x in list_number:
if x > number:
return True
return False
A property of if/else is that if one runs, the other doesn't. But in both cases, one runs. In your code, this snippet:
if x > number:
return True
else:
return False
Means that it will check if the number is bigger than the number in question. If it is, it will return True. If not, it will return False. A return call instantly ends the processing of a function, so it will stop checking after that.
To summarize, your code loops through the target list. It checks the first number, one, and sees if it is bigger than two. It is not, so the code returns False, instantly ending the function. So, your function just ended in a False, which is what it returned.
The change I made was that it returns False at the end of the code. This means that it will check each value for being greater than the target. If it finds any value greater than the target, it will end processing, with a return value of True. If the code hasn't returned by the time it reaches the end of the function, it will return False because of the statement at the end of the function.
Actually what happens is the else part also runs just after comparing the number (here 2) with the first element in the list_number (here 1) thus returns false.
So the solution is you need to let the for loop first run completely which is stopped by the else statement.
def has_gt(list_number,number):
for x in list_number:
if x > number:
return True
return False
Which code segment should replace the statement pass in the function hasEvenNumber which returns True if n contains an even number and False otherwise?
def hasEvenNumber(n):
for i in n:
pass # Replace this section with below options
return result
The question screenshot
This is an actual university exam question. I find it very badly structured and since my classmates are new too, nobody dared to voice out fearing to make a fool of themselves.
Firstly n was not given, but judging that n will be used in a for loop. n therefore, would be an iterable. I think none of the 4 options applies, but please advise me if I'm wrong.
Option 1:
if i % 2 == 0:
result = True
else:
result = False
This will only work if iterable only contains 1 item e.g [1,2,1] will not work since the result of 2 as even number that should return true will be replaced as the loop proceed to next iteration.
[1,2,1,1] False # Wrong, should be true
[1,1,1,2] True
[2] True
Option 2:
if i % 2 == 0:
result = True
break
else:
result = False
break
Worse than above, this will only iterate the first item and break regardless.
[1,2,1,1] False # Wrong, should be true
[1,1,1,2] False # Wrong, should be true
[2] True
Option 3:
if i % 2 == 0:
result = True
break
Function will have runtime error if no even number is found, the variable result will not be assigned.
[1,2,1,1] True
[1,1,1,1] Runtime Error
[2] True
[1] Runtime Error
Option 4:
if i % 2 != 0:
result = False
break
Same as above, runtime error. No variable will be assigned if all even numbers.
Personally, as the question asked to check if n contains even number. I would have written something like this.
# Break and exit loop once even number is found. Otherwise continue.
if i % 2 == 0:
result = True
break
else:
result = False
Unfortunately, this is not an option. Apologies if this is the wrong place to post this, but any advice would be gladly appreciated, and could possibly change the fate our my current school cohort.
Yes, you are right and little bit overthinking.
Third option is right and it is kinda assumed here that result is set to False in the beginning.
Also, your solution can be optimised by declaring result = False once in the beginning and then you can eliminate the else block completely.
If you want it to end when an even number is found, option 3.
In this code:
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_even(2))
print(is_odd(2))
I keep going through this in my head and wondering how it's working. It seems to me that eventually x in is_even(x) will return True every time. However, when I run the code, it works perfectly fine and returns True and False appropriately. Can someone explain how that's happening?
I understand the basic concept of recursion and fully understand how the famous factorial example works. However, this one is hard for me to wrap my head around.
Feeling inept right now...
It always helps to decompose a recurrence relation till you find its base case.
is_even(2) => return is_odd(1)
=> return not is_even(1)
=> return not is_odd(0)
=> return not not is_even(0)
=> return not not True
=> return True ---- (1)
is_odd(2) => return not is_even(2)
=> return not True [from (1)]
=> return False
In general, from your recurrence functions, it is easy to observe that is_even(n) will return [not not not ... n times] True, while is_odd(n) will return [not not not ... n - 1 times] True. So the number of nots and hence the final expression depend on n (aha!). Well, that's certainly a roundabout way of asking whether
n % 2 == 0
Add a couple of print statements and you will see what it is doing:
from __future__ import print_function
def is_even(x):
if x == 0:
print('True')
return True
else:
return is_odd(x-1)
def is_odd(x):
print('not', end=' ')
return not is_even(x)
>>> is_even(5)
not not not not not True
False
>>> is_odd(5)
not not not not not not True
True
Like in most cases it might be helpful to include simply prints to follow the execution:
def is_even(x):
print('check if {} is even'.format(x))
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
print('check if {} is odd'.format(x))
return not is_even(x)
Then in your cases:
>>> print(is_even(2))
check if 2 is even
check if 1 is odd
check if 1 is even
check if 0 is odd
check if 0 is even
True
>>> print(is_odd(2))
check if 2 is odd
check if 2 is even
check if 1 is odd
check if 1 is even
check if 0 is odd
check if 0 is even
False
So basically it decrements the number until it's 0. The point is just how many nots have been accumulated in the is_odd calls. If it's an even number of nots then the result will be True, otherwise False.
That's true; the recursion is supposed to end inside is_even.
And when that will happen, you'll know that the number you have is 0.
Now lets go backwards. This final state will be achieved by two cases - direct call to is_even(0) or a call from is_odd(0). In the first case - the result is all good. In the second - the result will be returned to the is_odd function, negated, and therefore will be falsy - giving a correct result.
Now, here the missing piece comes - the recursion: in order to reach this state, we need to decrease the argument each time, passing it through the opposite function - and that's exactly what we get with return is_odd(x-1).
Note: eventually this recursion leads to a chain of negations of the value True returned by the is_even. This chain is of length x where x is your number, and therefore odd or even in correspondence.
Therefore, the following code will do the same (lacking the is_odd nice side effect):
def is_even (x):
res = True
while x:
res = not res
x -= 1
return res
I think that all the other answers are great but potentially the easiest way to understand the problem is how many times the answer will get "not"ed. Every time it passes through the is_odd function a not will be added on to the final answer. True will always be returned but for even numbers, there will always be an even number of nots which cancel each other out, but for odd numbers they will always have an odd number of nots and therefore return false.
I have a really basic if/else logic question for Python. An exercise in the book required me to write a function that takes a list of integers are returns True if the list contains all even numbers and False if it doesn't.
I wrote:
list1 = [8,0,-2,4,-6,10]
list2 = [8,0,-1,4,-6,10]
def allEven(list):
for x in list:
if x % 2 != 0:
return False
else:
return True
This code always returns True. Why is that? Doesn't the code see the -1 during the loop of all the values of the list and returns the False?
list1 = [8,0,-2,4,-6,10]
list2 = [8,0,-1,4,-6,10]
def allEven(list):
for x in list:
if x % 2 != 0:
return False
return True
The book gives the answer of this. Why does this work and mine doesn't?
Pay close attention to where that else is placed. Indentation and nesting matters here!
In your first example, it will return True on the first element that satisfies your condition because your first if check fails.
In your second example, it will return True after all elements have been iterated through and a return value hasn't been produced.
The first function checks the first number only, since it returns something as soon as the for loop starts.
By the way, you can but should not use list as an argument or a variable name, since it is a keyword.
I strongly recommend writing a print statement to output x before both of your return statements. It will help you understand the flow of the code.
The short answer is that only the first element is being checked by your code, and the function returns True or False based on that value.
In the book solution, any failure causes a return of False, but the loop simply continues otherwise. Only if all elements are checked without failure does the return True reached.