Alejandro Rodriguez
Alejandro Rodriguez

Reputation: 23

How to split and keep float numbers together Ruby and Python

I am programming a math expression checker. I have this string:

oper = "((234+3.32)+(cos4-sin65))"

I want to split this string by separating all "()"s and operators minus numbers or trigonometric ratios to get this result:

oper = ['(', '(', '234', '+', '3.32', ')', '+', '(', 'cos4', '-', 'sin65', ')', ')']

How would the split be?

Upvotes: 1

Views: 111

Answers (3)

user6035995
user6035995

Reputation:

There is an easier way, use it:

oper = "((234+3.32)+(cos4-sin65))"
separators=["(",")","+","-"]

def my_split(o, l, j="@"):
    for e in l:
        o = o.replace(e, j+e+j)
    return [e for e in o.split(j) if e]

print(my_split(oper, separators))

Upvotes: 0

steenslag
steenslag

Reputation: 80065

Ruby:

oper = "((234+3.32)+(cos4-sin65))"
re = Regexp.union("(" ,")", "+", "-", /[^()\-+]+/)
p oper.scan(re) # => ["(", "(", "234", "+", "3.32", ")", "+", "(", "cos4", "-", "sin65", ")", ")"]

Upvotes: 1

Filip Młynarski
Filip Młynarski

Reputation: 3612

Here's my example solution.

oper = "((234+3.32)+(cos4-sin65))"
separators = ['(', ')', '+', '-', 'cos', 'sin']

def sep_at_beg(x):
    for separator in separators:
        if len(x) >= len(separator) and x.startswith(separator):
            if separator in ['cos', 'sin']:
                if len(x) > len(separator)+1 and x[len(separator)+1].isdigit():
                    return x[:len(separator)+2]
                return x[:len(separator)+1]
            return separator
    return False

def separate(x):
    return_x = []
    idx = 0
    so_far = ''
    while idx < len(x):
        separator = sep_at_beg(x[idx:])
        if separator:
            if so_far:
                return_x.append(so_far)
            return_x.append(separator)

            so_far = ''
            idx += len(separator)
        else:
            so_far += x[idx]
            idx += 1
    if so_far:
        return_x.append(so_far)
    return return_x

oper = separate(oper)
print(oper)

Outputs:

['(', '(', '234', '+', '3.32', ')', '+', '(', 'cos4', '-', 'sin65', ')', ')']

Upvotes: 1

Related Questions