Before I debug my code, I would like to know why there's an error occurred when I call the function? It says "NameError: name 'stDigs' is not defined". I've tried using "avgUntilLetter(0123a)" and "avgUntilLetter("0123a")" but none of them works. Help me plz!
This function receives as input one string containing digits or letters. The function should return one float number contaning the average calculated considering all the digits in the string starting form the first position and considerign all digits until one letter is found or until reaching the end of the string.
An example: avgUntilLetter('0123a456') should return 1.5
def avgUntilLetter (stDigs):
num = 0
each_char = stDigs[num]
while each_char.isdigit() == True and num < len(stDigs):
num = num + 1
each_char = stDigs[num]
digits = stDigs[0:num]
avg = sum(digits)/len(digits)
return avg
avgUntilLetter(stDigs)
Yes, I know there are a lot errors needed to be solved. I just need to solve it one at a time. When I call the function using "avgUntilLetter ("0123a")", the defined error disappeared but a type error popped up. Hmm.. I'm still keeping trying it.
There are several problems in your code:
You can end up trying to access stDigs[len(stDigs)]
because num < len(stDigs)
might be true, but you then add 1 before using it as an index.
sum(digits)
won't work because digits
is a string.
Just loop over the string directly instead of using a while
loop, add up the digits in the loop:
def avgUntilLetter(stDigs):
total = i = 0
for i, each_char in enumerate(stDigs):
if not each_char.isdigit():
break
total += float(each_char)
if i:
return total / i
return 0.0
This handles edge-cases as well:
>>> avgUntilLetter('0123a456')
1.5
>>> avgUntilLetter('')
0.0
>>> avgUntilLetter('abc')
0.0