pythonstring

Find the sum and average of the numbers within a string(/sentence), ignoring all the characters


I need help to get the output

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.

Test Cases:

  1. Input

    I am 25 years and 10 months old

    Output

    35 17.5

The test case above is pretty straightforward and simple, my problem comes when you trying to solve something like this.

  1. Input

    A girl64 35spaces numb6rs

    Output

    05 66.66

So basically what I am asking is, how do you extract the digits that's existing between a string of characters. To make it so that (164) does not become (1,6,4).

  1. Input

    1time3 %times4

    Output

    8 2.67

This is another case where (1,3) shouldn't be extracted as 13 as in test case 2. This is the exact case where I need help.

The code that I have worked up and this worked for me to just get the numbers which are not part of the word itself, and this worked well for the case 1:

sentence=input().split()
op=[]
for i in sentence:
    if i.isdigit():
        op.append(int(i))
    else:
        for j in i:
            if j.isdigit():
                op.append(int(j))
print(sum(op))
avg=sum(op)/len(op)
print(round(avg,2))

I have found this while searching for a clue and this worked for test cases 1 and 2 but still is failing for the third one since it joins the numbers from the same word irrespective of the position.

a=input()
a=a.split()
t=[int(''.join([j for j in k if j.isdigit()])) for k in a if any(m.isdigit() for m in k)]
print(t)
if len(t)!=0:
    print(sum(t))
    print(sum(t)/len(t))
else:
    print(sum(t))
    print(sum(t))

I couldn't understand the code above but hoping someone would clarify me and suggest me how to solve this problem.


Solution

  • If your numbers are positive integers you can use below logic to extract them:

    input_str = "1time3 %times4"
    
    numbers = ''.join((ch if ch in '0123456789' else ' ') for ch in input_str)
    numbers_list = [int(i) for i in numbers.split()]
    
    print(f"Extracted numbers: {numbers_list}")
    print(f"Sum: {sum(numbers_list)}, Average: {sum(numbers_list)/ len(numbers_list)}")