Numbers in String - 1
Given a string, write a program to return the sum and average of the digits of all 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 digits of all 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 digits of all numbers that appear in the string are 2, 5, 1, 0. Your code should print the sum of all digits(8) and the average of all digits(2.0) in the new line.
Sample Input 1
I am 25 years and 10 months old
Sample Output 1
8
2.0
Sample Input 2
Tech Foundation 35567
Sample Output 2
26
5.2
def SumAndAverage(str1):
# A temporary string
temp = "0"
# holds sum of all numbers present in the string
Sum = 0
#counter of numbers in row
count=0
# read each char
for ch in str1:
# if char is a digit
if (ch.isdigit()):
temp += ch
# if current character is not digit
else:
if temp!="0":
count+=1
Sum += int(temp)
# reset temporary string
temp = "0"
if str1[-1].isdigit():
count+=1
Sum += int(temp)
# print sum of numbers
print(Sum)
# print average of nubers
print(Sum / count)
# Main code
# input the string
print("Input the string")
str1 = input()
# Function call
SumAndAverage(str1)
Comments
Leave a comment