Skip to content

create sum_of_digits.py#2065

Merged
cclauss merged 5 commits into
TheAlgorithms:masterfrom
vicky1999:patch-2
Jun 2, 2020
Merged

create sum_of_digits.py#2065
cclauss merged 5 commits into
TheAlgorithms:masterfrom
vicky1999:patch-2

Conversation

@vicky1999
Copy link
Copy Markdown
Contributor

@vicky1999 vicky1999 commented Jun 2, 2020

create sum_of_digits.py to find the sum of digits of a number
digit_sum(12345) ---> 15
digit_sum(1234) ---> 10

vicky1999 added 2 commits June 2, 2020 22:33
create sum_of_digits.py to find the sum of digits of a number
digit_sum(12345) ---> 15
digit_sum(12345) ---> 10
Comment thread maths/sum_of_digits.py Outdated
Comment thread maths/sum_of_digits.py
"""
res = 0
while n > 0:
res += n % 10
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we optimize using Python builtin https://docs.python.org/3/library/functions.html#divmod ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, divmod() method would be faster than mod operator. But for small values, there is not much difference. Everytime, we mod a number with 10 until it becomes 0 will not have much effect on the running time I guess.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

def digits(n):
        while n:
            n, digit = divmod(n, 10)
            yield digit
         
print(sum(digits(12345)))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that's the digit sum function using divmod()

Comment thread maths/sum_of_digits.py Outdated
vicky1999 and others added 3 commits June 3, 2020 01:19
Co-authored-by: Christian Clauss <cclauss@me.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
@cclauss cclauss merged commit 0904610 into TheAlgorithms:master Jun 2, 2020
stokhos pushed a commit to stokhos/Python that referenced this pull request Jan 3, 2021
* create sum_of_digits.py

create sum_of_digits.py to find the sum of digits of a number
digit_sum(12345) ---> 15
digit_sum(12345) ---> 10

* Update sum_of_digits.py

* Update maths/sum_of_digits.py

Co-authored-by: Christian Clauss <cclauss@me.com>

* Update maths/sum_of_digits.py

Co-authored-by: Christian Clauss <cclauss@me.com>

* Update sum_of_digits.py

Co-authored-by: Christian Clauss <cclauss@me.com>
GlennCheng pushed a commit to GlennCheng/Python that referenced this pull request Apr 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants