I was trying to solve this problem when I thought of implementing the operator inside the return statement. Here is the question:
Digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer. Examples:
Code:
def digital_root(n):
return w:=sum(int(x) for x in str(n)) if w<10 else digital_root(w)
To use the walrus operator, you should put it where the if
condition is:
def digital_root(n):
return w if (w := sum(int(x) for x in str(n))) < 10 else digital_root(w)
That's basically a shorter version of this:
def digital_root(n):
if (w := sum(int(x) for x in str(n))) < 10:
return w
else:
return digital_root(w)