Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

AdvancedPhase 6 - Category 2: Array & String CombinationsExample 6 of 10
sum-of-numbers-in-array-of-strings.py
1# Take array of strings
2n = int(input("Enter number of strings: "))
3arr = []
4for i in range(n):
5 arr.append(input(f"String {i+1}: "))
6
7# Extract and sum numbers
8total = 0
9for s in arr:
10 current_num = ""
11 for char in s:
12 if char.isdigit():
13 current_num += char
14 else:
15 if current_num:
16 total += int(current_num)
17 current_num = ""
18 if current_num:
19 total += int(current_num)
20
21print(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. 1

    Begin every string with an empty current_num.

  2. 2

    Add completed digit runs to the shared total.

  3. 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.