[Tutor] Converting integers into digit sum (Python 3.3.0)
spir
denis.spir at gmail.com
Mon Dec 9 14:23:16 CET 2013
On 12/09/2013 09:08 AM, Rafael Knuth wrote:
> Hej there,
>
> I wrote a program that converts an integer into a digit sum:
>
> def DigitSum(YourNumber):
> DigitList = []
> YourNumber = str(YourNumber)
> for i in YourNumber:
> DigitList.append(int(i))
> print(sum(DigitList))
>
> DigitSum(55)
>
>>>>
> 10
>
> It actually works but I was wondering if that's the only way to solve
> the task of converting an integer into a digit sum? I learned from
> past conversations on this mailing list that often times there is a
> better, more elegant and shorter way to write a program, and I was
> wondering if that's the case here.
Tu sum it up (aha!): you algorithm is the right and only one, but there are ways
in python to express it more succintly, if not elegantly.
What is missing is checking that the input is actually a natural number
(unsigned integer), and a number at all. In particular, I guess from the name
YourNumber it is supposed to come from user input. (In the following, I stop the
program with an error message, because you may not know yet about exceptions and
exception catching.)
Another point is changing the name of the str variable: it does not mean the
same thing and represents another programming element, so should not be called
the same way. Since we are at naming:
* In python common conventions, names with capitals (as yours) represent
programmer-defined types (you may not know that yet), rather than functions or
simple variables.
* Your function name looks like telling us it produces a sum, while instead it
writes it.
Without using comprehensions (maybe a little advanced), you can still (learn to)
directly traverse a string as a sequence of digit characters
All in all, it could look like:
def write_digit_sum (your_number):
# Check input:
# (Python has not type for natural numbers.)
if (type(your_number) is not int) or (your_number < 0):
msg = "Input to 'write_digit_sum' should be a natural number. Found: "
print(msg + repr(your_number)) # using repr in case it is a string
exit()
# If we arrive here, your_number is ok.
# Write sum:
numeral = str(your_number)
summ = 0
for digit in numeral:
summ += int(digit)
print(summ)
def test_write_digit_sum ():
write_digit_sum(0)
write_digit_sum(1)
write_digit_sum(345)
write_digit_sum(999999999)
# execution failures on invalid input:
# (to comment out once tested)
#~ write_digit_sum(-1)
#~ write_digit_sum(1.1)
#~ write_digit_sum('a')
write_digit_sum((1,2,3))
test_write_digit_sum()
Denis
More information about the Tutor
mailing list