I'm new to python and was looking around for a code for a function where the user inputs and integer and the function adds and returns the sum of the digits of the number.
The code looked like this:
def sum_digits(n):
s = 0
while n:
s += n % 10
n //= 10
return s
So I know how a while loop works, but I can't wrap my head around (nor am able to find anything on Google) about how this works. I thought While loops always have a condition such as 'while n<10' or the sort.
What exactly is 'while n:' saying? How does this code work exactly? How does the code know how to stop running, and how exactly does it even return the sum of the digits (all I see it doing is returning the remainder of s/n).
Thanks for the help and sorry for any stupid questions.
while implicitly calls bool on the argument. So as long as bool(n) in your example is True the while loop continues.
And Pythons documentation for builtin types states that any number except zero is considered True:
By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:
constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)
So basically the while n loop will continue until n becomes zero (or you break or return or raise...)
while n: is equivalent to while n!=0: (in this case, when you're dealing with numbers). Since each value in python has a Boolean value, for any number that is different from zero, bool(n) == True, if n equals zero, bool(n) == False.
That function can be written like (Thanks to #Jean-FrançoisFabre for suggesting the use of divmod):
def sum_digits(n):
s = 0
while n != 0:
n, t = divmod(n, 10) # to not use division and modulo separately
# n has the value of n//10, t has the value of n%10
s += t
return s
print(sum_digits(154)) # => 10
print(sum_digits(134)) # => 8
print(sum_digits(987)) # => 24
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/
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!
I have a code that checks if a given list of integers can sum up to a specified target. If any combination of the integers in a list can sum up to a target value, it returns True. The input 'start' is the index of the list that I want to start from and continue until the end of the list
def groupSum(start, nums, target):
if start >= len(nums):
return target == 0
else:
return groupSum(start + 1, nums, target - nums[start]) or groupSum(start + 1, nums, target);
So, if I put
groupSum(0, [2,4,8], 10)
it will return True, and, if I put
groupSum(0, [2,4,8], 9)
it will return False
QUESTION: I don't understand how they can put 'or' in the return statements, in a recursive case. I don't see how that's actually working. Is it passing multiple functions simultaneously to check every combination or what?
I'm pretty new to Recursion method and would appreciate it if you can explain the technique used here. Thanks
In python and and or operators, do not return boolean values. They return the last thing evaluated. So, when you
return a or b
if a is a truthy value, a will be returned. Otherwise, the truthness of the expression depends on b, and so b will be returned.
Why it's True for 10 is because there's an exact match for 10 (8+2); which your recursive function reduces to 0 for the target variable.
So, groupSum(start + 1, nums, target - nums[start]) this becomes True - so the comparison will be True or False, which will turn out to True!
Now, for the value of 9, there's no such match and hence it'll always remain False.
You can try for 12 and 6 as well. It'll return True.
Whereas, for any other value the comparison will always be False or False.
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 don't know if this has been asked before but here I go.
A while loop takes a bool, something like while a<5 or while True and proceeds to do something.
n = 10000
count = 0
while n:
count = count + 1
n = n / 10
n=int(n)
print (count)
This code will execute the while loop, but why, I understand that I could use 1 instead of True, but here it's going like "while 10000", and 10000 != True, so how does that work?
Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to convert any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).