Home > Enterprise >  Extracting number from alphanumeric string and adding them
Extracting number from alphanumeric string and adding them

Time:01-28

Given string str containing alphanumeric characters. The task is to calculate the sum of all the numbers present in the string.

Example 1:

Input:
str = 1abc23
Output: 24
Explanation: 1 and 23 are numbers in the
a string which is added to get the sum as
24.

Example 2:

Input:
str = geeks4geeks
Output: 4
Explanation: 4 is the only number, so the
the sum is 4.

I broke down the problem into smaller parts, for first I just want to extract the numbers.

s = "a12bc3d"

number = ""
for i in range(0, len(s)):
    if s[i].isdigit():
        n=0
        number = number   s[i]
        while s[i].isdigit():
            n = n 1
            if s[i   n].isdigit():
                number = number   s[i n]   " "
            else:
                break
            i = i   n   1
    else:
        continue


print(number)

my output from the above code is 12 23 but it should be 12 3, as the for loop is starting from the initial point making 2 coming twice, I have tried to move the for loop forward by updating i = i n 1 but it's not working out like that. It will be great if someone gives me a direction, any help is really appreciated.

CodePudding user response:

A slightly simpler approach with regex:

import re

numbers_sum = sum(int(match) for match in re.findall(r'(\d )', s))

CodePudding user response:

Use itertools.groupby to break the string into groups of digits and not-digits; then convert the digit groups to int and sum them:

>>> from itertools import groupby
>>> def sum_numbers(s: str) -> int:
...     return sum(int(''.join(g)) for d, g in groupby(s, str.isdigit) if d)
...
>>> sum_numbers("1abc23")
24
>>> sum_numbers("geeks4geeks")
4

CodePudding user response:

you can use regex.

import re
s='a12bc3d'
sections = re.split('(\d )',s)
numeric_sections = [int(x) for x in sections if x.isdigit()]
sum_ = sum(numeric_sections)
print(sum_)
  •  Tags:  
  • Related