Search code examples
pythonpython-3.xstringlistlist-comprehension

How to calculate sum of numbers separated by a special symbol?


Suppose I have a string containing the following:

'*as**4fgdfgd*vv**6fdfd5***5'

String contains numbers, letters, and a special symbol such as an asterisk.

  • I need to find the sum of numbers (4,6) (5,5) separated by asterisk.
  • The number of asterisks between two numbers must be equal to 3.
  • Return True if sum of every pair is equal to 10.

Examples:

  • *as**4fgdfgd*vv**6fdfd5***5 returns True.
  • ssss*0***10jkj* **0***10 returns True.
  • 5***5***5 returns True because there 3 asterisks between the numbers and sum equals 10.
  • 8**‍‍‍‌‍‌‌‌‌‌‌‍‌‍‍‌‍‍2 returns False

My Code So far:

my_str = "*as**4fgdfgd*vv**6fdfd5***5"

my_digits = [int(x) for x in my_str if x.isnumeric()]

print(sum(my_digits))

Solution

  • You can use a regex to find pairs of numbers that are separated by 3 asterisks, then convert the found numbers to int and add them, returning true if all pairs add to 10. Note that because you want overlapping matches, we need to use a lookahead as described in this question.

    def all_tens(my_str):
        pairs = re.findall(r'(?=(?<!\d)(\d+)(?:[^*\d]*\*){3}[^*\d]*(\d+))', my_str)
        return len(pairs) > 0 and all(sum(map(int, pair)) == 10 for pair in pairs)
    
    strs = [
     '*as**4fgdfgd*vv**6fdfd5***5', 'ssss*0***10jkj* **0***10', '5***5***5', '8**‍‍‍‌‍‌‌‌‌‌‌‍‌‍‍‌‍‍2', '5***5***4'
    ]
    for s in strs:
        print(f'{s} : {all_tens(s)}')
    

    Output:

    *as**4fgdfgd*vv**6fdfd5***5 : True
    ssss*0***10jkj* **0***10 : True
    5***5***5 : True
    8**2 : False
    5***5***4 : False
    

    Regex explanation:

    (?=(?<!\d)(\d+)(?:[^*\d]*\*){3}[^*\d]*(\d+)(?!\d))
    
    • (?= a lookahead (we use this to allow overlapping matches)
    • (?<!\d) the preceding character must not be a digit
    • (\d+) some digits, captured in group 1
    • (?:[^*\d]*\*){3} 3 sets of an asterisk, which may be preceded by some number of characters which are neither asterisks or digits
    • [^*\d]* some number of characters which are not asterisk or digits
    • (\d+) some digits, captured in group 2