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.
Input 1:-
I am 25 years and 10 months old
Output 1:-
35
17.5
Input 2:-
Tech Foundation 35567
Output 2:-
35567
35567.0
We want given both inputs they can get both outputs we code was run one by one input and output
def GetSum(s):
s = s.split(" ")
Sum=0
Mean=0
c=0
for r in range(len(s)):
if(s[r].isnumeric()):
Sum = Sum + int(s[r])
c=c+1
Mean = float(Sum/c)
print("\nInput: ",InputStr)
print("Output:")
print(Sum)
print(Mean)
return(Sum,Mean)
InputStr = "I am 25 years and 10 months old"
Sum,Mean = GetSum(InputStr)
InputStr = "Tech Foundation 35567"
Sum,Mean = GetSum(InputStr)
Comments
Leave a comment