DEV Community

Discussion on: Daily Challenge #264 - Digital Root

Collapse
 
agtoever profile image
agtoever • Edited

Python 3 using direct calculation. Defined as function with test cases in the tio link.

digital_root = lambda n: 0 if n == 0 else 1 + (n - 1) % 9

Try it online!

Collapse
 
rafaacioly profile image
Rafael Acioly

why 1 + (n - 1)?

Collapse
 
j_mplourde profile image
Jean-Michel Plourde

I tested it with just n and it works fine.

Collapse
 
dry profile image
Hayden Mankin

It's important to remember that the % operator happens before +, this solves the edge cases around numbers divisible by 9 without needing extra if statements/ternaries.

For instance,

18 -> 1 + 8 = 9

however,

18 % 9 = 0

which does not fit the problem specification, so instead we do

(18 - 1) % 9 + 1 = 17 % 9 + 1 = 8 + 1 = 9