if i just read my sum_digits
function here, it makes sense in my head but it seems to be producing wrong results. Any tip?
def is_a_digit(s):
''' (str) -> bool
Precondition: len(s) == 1
Return True iff s is a string containing a single digit character (between
'0' and '9' inclusive).
>>> is_a_digit('7')
True
>>> is_a_digit('b')
False
'''
return '0' <= s and s <= '9'
def sum_digits(digit):
b = 0
for a in digit:
if is_a_digit(a) == True:
b = int(a)
b += 1
return b
For the function sum_digits
, if i input sum_digits('hihello153john')
, it should produce 9
An equivalent for your code, using list comprehensions:
It will run faster then a "for" version, and saves a lot of code.
Just a variation to @oscar's answer, if we need the sum to be single digit,
Another way of doing it:
Notice that you can easily solve this problem using built-in functions. This is a more idiomatic and efficient solution:
In particular, be aware that the
is_a_digit()
method already exists for string types, it's calledisdigit()
.And the whole loop in the
sum_digits()
function can be expressed more concisely using a generator expression as a parameter for thesum()
built-in function, as shown above.One liner
Another way of using built in functions, is using the reduce function: