Add Numbers in Unclean Data

Given a string such as as+v123bjh^-25j6, return the operation of the elements in the string summed together. In this case, it would be 123 - 25 + 6.

The Idea: Parse the string by all digits, or the - seperator. We can ignore + since numbers are by default assumed to be positive. Then take this list of patterns, and filter out everything by the delimitors, which in our case includes the digits and the sign. Finally, iterate through the filtered list, and sum the elements. Keep a flag for negative tokens.

Complexity: O(n) time and space

import re, operator


def clean_n_calc(str):
    my_op = {'-': operator.sub}
    clean_data = [token for token in re.split('(\d+|-)', str) if token.isdigit() or token == '-']
    sum, neg = 0, 1
    for token in clean_data:
        if token.isdigit():
            sum += (int(token) * neg)
            neg = 1
        else:
            neg = -1
    return(sum)


print(clean_n_calc('as+v123bjh^-25j6'))

Last updated