Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find sum of digits that are inside one alphanumeric string in Python
Suppose we have an alphanumeric string with digits from "0" to "9" and lowercase English letters. We need to find the sum of all numbers present in the string. If digits are consecutive, they form a single number.
For example, if the input is s = "hello25world63power86", the output will be 174 because 25 + 63 + 86 = 174.
Algorithm
To solve this problem, we follow these steps −
Initialize
ret = 0(final sum) andcurr = 0(current number being built)-
For each character in the string:
If character is a digit, build the current number:
curr = 10 * curr + digitIf character is not a digit, add current number to result and reset:
ret += curr,curr = 0
Return
ret + curr(add the last number if string ends with digits)
Example
Let us see the implementation to get better understanding −
def solve(s):
ret = 0
curr = 0
for ch in s:
if ch.isdigit():
curr = 10 * curr + int(ch)
else:
ret += curr
curr = 0
return ret + curr
s = "hello25world63power86"
print(solve(s))
174
How It Works
For the string "hello25world63power86" −
h,e,l,l,o: Not digits,
currremains 02,5: Digits,
curr = 0*10+2 = 2, thencurr = 2*10+5 = 25w: Not digit,
ret = 0 + 25 = 25,curr = 06,3: Digits,
curr = 63p: Not digit,
ret = 25 + 63 = 88,curr = 08,6: Digits,
curr = 86End of string:
ret = 88 + 86 = 174
Alternative Approach Using Regular Expressions
import re
def solve_regex(s):
numbers = re.findall(r'\d+', s)
return sum(int(num) for num in numbers)
s = "hello25world63power86"
print(solve_regex(s))
174
Conclusion
Use the iterative approach for better understanding of the algorithm. The regex approach is more concise but requires importing the re module. Both methods efficiently extract and sum consecutive digits from alphanumeric strings.
