Sum of Numbers in Array of Strings
Sum digit runs found across multiple strings. Students reset a per-string buffer, keep a shared total, and flush trailing numbers before moving to the next text.
1# Take array of strings2n = int(input("Enter number of strings: "))3arr = []4for i in range(n):5 arr.append(input(f"String {i+1}: "))67# Extract and sum numbers8total = 09for s in arr:10 current_num = ""11 for char in s:12 if char.isdigit():13 current_num += char14 else:15 if current_num:16 total += int(current_num)17 current_num = ""18 if current_num:19 total += int(current_num)2021print(f"Total sum: {total}")
Output
Enter number of strings: 3 String 1: Hello123 String 2: World456 String 3: Test789 Total sum: 1368
In this one
- Reset per-string buffers
- Share an overall total
- Flush each trailing number
How it works
- 1
Begin every string with an empty current_num.
- 2
Add completed digit runs to the shared total.
- 3
Flush the final run before moving to the next string.
Edge cases
Why reset the buffer for every string?
Why reset the buffer for every string?
Runs must not continue across separate strings.
Do minus signs make negative values?
Do minus signs make negative values?
No. They are separators in this parser.
What's going on
Each string begins with an empty current_num. Adjacent digit characters form a whole-number run, which is added when a nondigit arrives.
The end-of-string flush prevents a trailing run from being lost or joined to the next string. For a12 and b3, the shared total is fifteen. Signs and decimal points act as separators, not numeric syntax. Unicode digit parsing retains the same int limitations.
Why reset the buffer for every string? Runs must not continue across separate strings.
Do minus signs make negative values? No. They are separators in this parser.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which value remains shared across strings?
Pick an answer to check it.
Question 2
Why reset the buffer for every string?
Pick an answer to check it.
Questions people ask
Why reset the buffer for every string?
Runs must not continue across separate strings.
Do minus signs make negative values?
No. They are separators in this parser.
Which value remains shared across strings?
total.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum