Skip to content

Sum Up Numbers

CodeMaster has just returned from shopping. He scanned the check of the items he bought and gave the resulting string to Ratiorg to figure out the total number of purchased items. Since Ratiorg is a bot he is definitely going to automate it, so he needs a program that sums up all the numbers which appear in the given input.

Help Ratiorg by writing a function that returns the sum of numbers that appear in the given inputString.

Example

For inputString = "2 apples, 12 oranges", the output should be

sum_up_numbers(inputString) = 14

Solution

py
import re


def sum_up_numbers(input_string):
    return sum(int(number) for number in re.findall(r'\d+', input_string))


print(sum_up_numbers('2 apples, 12 oranges'))
print(sum_up_numbers('there are some (12) digits 5566 in this 770 string 239'))
print(sum_up_numbers('42+781'))
js
// import re

// def sum_up_numbers(input_string):
//     return sum(int(number) for number in re.findall(r'\d+', input_string))

// print(sum_up_numbers('2 apples, 12 oranges'))
// print(sum_up_numbers('there are some (12) digits 5566 in this 770 string 239'))
// print(sum_up_numbers('42+781'))

// Input:
// inputString: "abcdefghijklmnopqrstuvwxyz1AbCdEfGhIjKlMnOpqrstuvwxyz23,74 -"
// Expected Output:
// 98
function sumUpNumbers(inputString) {
  return inputString
    .split(/[^0-9]/)
    .filter((number) => number !== '')
    .reduce((sum, number) => sum + parseInt(number), 0);
}

console.log(sumUpNumbers('Your payment method is invalid'));

my thoughts are neither my employer's nor my wife's