Search code examples
pythonalgorithmrecursionmathwalrus-operator

Why is the Walrus Operator not working when implemented inside the return statement of this function?


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:

  1. 16 --> 1 + 6 = 7
  2. 493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
  3. 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6

Code:

def digital_root(n):
    return w:=sum(int(x) for x in str(n)) if w<10  else digital_root(w)

Solution

  • 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)