Python Shorts — Digits Sum

John Clark Craig
4 min readFeb 22, 2023

There’s one algorithm that’s 25 times faster!

Image courtesy of DALL-E

Every once in a while, I come across some discussion involving number games or other interesting math, where the sum of all the digits in an integer is to be found repeatedly until only one digit is left. I decided to write a short Python function to do this calculation, so I could add it to my bag of Python tricks.

I learned a lot and discovered one algorithm that’s amazing!

It turns out there are several algorithms and approaches to finding this sum-of-digits. Each algorithm demonstrates unique Python features, so it’s worth taking a quick look at how they each work.

ChatGPT’s answer

I started by asking ChatGPT to create a function to find the sum of the digits in an integer. I had to modify the code a little, to repeat the calculation until only one digit was left. This is the longest function in the list, but it runs pretty fast and gets the job done.

def digits1(num):
num_str = str(num)
while len(num_str) > 1:
s = 0
for digit in num_str:
s += int(digit)
num_str = str(s)
return int(num_str)

Here’s how I called this function, with the results shown in the comments at the end of each line.

print(digits1(437))  # 5…

--

--

John Clark Craig

Author, inventor, entrepreneur — passionate about alternate energy, technology, and how Python programming can help you hack your life.