2017-05-26 213 views
0

我有一個字符串,如 '(((a+b)+a)+c)',我想分成兩部分,結果是('((a+b)+a)','c')在python3中將字符串方程分成兩部分

如果我要的結果的第一個元素上再次運行它,它會給我('(a+b)', 'a')

,如果我又跑它'(a+b)'它會返回('a', 'b')

我想我可以通過一個正則表達式做到這一點,但我不知道這一點,然後走下路徑有許多if語句檢查打開和關閉括號,但它變得有點凌亂

+0

不知道這是怎麼太廣... – dimebucker91

+0

自發性我說你需要一個解析器。 – klutt

+0

@ dimebucker91你真正想要做的是解決操作或簡單地拆分字符串? (((a + b)+ c)+(a + b))( –

回答

1

這裏是上的例子,如你的工作的一個示例:

def breakit(s): 
    count = 0 
    for i, c in enumerate(s): 
     if count == 1 and c in '+-': 
      return s[1:i].strip(), s[i+1:-1].strip() 
     if c == '(': count +=1 
     if c == ')': count -= 1 
    return s 

breakit(s) 
>> ('((a+b)+a)', 'c') 
breakit(_[0]) 
('(a+b)', 'a') 
breakit(_[0]) 
('a', 'b') 
1

瞧的:

#!/usr/bin/python3.5 
def f(s): 
    p=s.rsplit('+',1) 
    return [p[0][1:],p[1][:-1]] 

s='(((a+b)+a)+c)' 

for i in range(3): 
    k=f(s) 
    s=k[0] 
    print(k) 

輸出:

['((a+b)+a)', 'c'] 
['(a+b)', 'a'] 
['a', 'b'] 
+0

分割出來,並不適用於所有情況。 – dimebucker91

0

我想我會發布我的回答爲好,不是很優雅的選擇的解決方案,但它的工作原理

def break_into_2(s): 

    if len(s) == 1: 
     # limiting case 
     return s 

    # s[0] can either be a digit or '(' 
    if s[0].isdigit(): 
     # digit could be 10,100,1000,... 
     idx = 0 
     while s[idx].isdigit(): 
      idx += 1 
     a = s[:idx] 
     b = s[idx+1:] 
     return a, b 
    # otherwise, s[0] = '(' 
    idx = 1 
    counter = 1 
    # counter tracks opening and closing parenthesis 
    # when counter = 0, the left side expression has 
    # been found, return the idx at which this happens 
    while counter: 
     if s[idx] == '(': 
      counter+=1 
     elif s[idx] == ')': 
      counter -=1 
     idx +=1 
    if s[:idx] == s: 
     # this case occurs when brackets enclosing entire expression, s 
     # runs the function again with the same expression from idxs 1:-1 
     return break_into_2(s[1:-1]) 
    return s[:idx], s[idx+1:]