Archive

Posts Tagged ‘sum’

Sum the digits of a number until you get just one digit

Problem

Take a positive integer and sum its digits. Repeat this process until you get just one digit.

Example: 1472 🠖 1+4+7+2 = 14 🠖 1+4 = 5. The answer is 5.

Solution

# Python code
n = 1472
result = ((n-1) % 9) + 1

Credits

Thanks to my friend Mocsa who told me this math trick.

Categories: python Tags: , ,

Product of the elements in a list

April 14, 2012 1 comment

Design goal: should be just one line, without using explicit iteration over the list.

Sum of the elements:

>>> li = [2,3,5]
>>> sum(li)
10

Product of the elements:

>>> li = [2,3,5]
>>> from operator import mul
>>> reduce(mul, li)
30
Categories: python Tags: , ,