Answer to Question #199676 in Python for meghana

Question #199676

Given a string, write a program to return the sum and average of the numbers that appear in the string, ignoring all other characters.Input


The input will be a single line containing a string.Output


The output should contain the sum and average of the numbers that appear in the string.

Note: Round the average value to two decimal places.Explanation


For example, if the given string is "I am 25 years and 10 months old", the numbers are 25, 10. Your code should print the sum of the numbers(35) and the average of the numbers(17.5) in the new line.




1
Expert's answer
2021-05-27T19:07:56-0400
s = input('Input string: ')
num_list = []
temp = ''
for char in s:
    if char.isdecimal():
        temp += char
    else:
        if temp:
            num_list.append(int(temp))
            temp = ''
else:
    if temp:
        num_list.append(int(temp))
        temp = ''
print(f'Sum: {sum(num_list)}')
print(f'Average: {round(sum(num_list) / len(num_list), 2)}')

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS