2

Please don't mark this question as duplicate as I have already seen the other questionSum of digits

Well, I have a following code

string = "2x83u0x7u8i9lkueieueue8"

numeric = lambda x: int(x) if x.isdigit() else 0
print reduce(lambda x, y: x + numeric(y), string , 0)

The answer should be 2 + 83 + 0 + 7 + 8 + 9 + 8 = 117 and not 45

Community
  • 1
  • 1
paddu
  • 693
  • 1
  • 7
  • 19

2 Answers2

2

The simplest way is to use a regex:

import re

string = "2x83u0x7u8i9lkueieueue8"

print(sum(map(int, re.findall("\d+", string))))

"\d+" finds 1 or more digits, so we just map the resulting list of string digits to int and sum

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

reduce() always operates on each item in an iterable individually. In this case, that means that the substring "83" is treated by your code as the integer 8 and the integer 3, not 83. You need to change your approach if you want to correctly handle multi-digit values.

bgporter
  • 35,114
  • 8
  • 59
  • 65