python - Combine the numbers in the brackets adjacently -


i want write function combine numbers in brackets adjacently. example, string input

(4)2(2)(2)(2)2(2) 

i want output is

(4)2(6)2(2) 

and example, string input

(2)(2)2(2)(2)(2)24 

i want output is

(4)2(6)24 

currently wrote function follows:

def combine(i,accumulate,s):     if s[i] == '(':         accumulate += int(s[i+1])         in range(i+3,len(s),3):             if s[i] == '(':                 accumulate += int(s[i+1])             else:                 print s[i-3] + s[i-2] + s[i-1]                 += 3                 break     else:         print s[i]         += 1   combine(0,0,'(4)2(2)(2)(2)2(2)') 

and output only:

(4) 

i know maybe need recursive method, don't know how use correctly. can me?

and treat one-digit problem, , after sum, need convert number more 9 corresponding alphabet.

following function:

def tostr(n,base): convertstring = "0123456789abcdefghijklmnopqrstuvwxyz" if n < base:   return convertstring[n] else:   return tostr(n//base,base) + convertstring[n%base] 

so example, input(the base 17):

(16)

the output needs be:

(g)

because don't know how modify function

re.sub(r'((\(\d\))+)', f, '(2)(2)(2)(2)(2)(2)(2)(2)') 

thanks.

i'd use regex that:

import re  def f(m):     return '({0})'.format(sum(int(x) x in m.group(1)[1::3]))  re.sub(r'((\(\d\))+)', f, '(4)2(2)(2)(2)2(2)') # (4)2(6)2(2) 

the second argument of re.sub can function, can use compute sum:

if repl function, called every non-overlapping occurrence of pattern. function takes single match object argument, , returns replacement string.

m.group(1) matched string, m.group(1)[1::3] matched string without parentheses.

sum(int(x) x in m.group(1)[1::3]) gets sum of digits in string.

'({0})'.format(sum(int(x) x in m.group(1)[1::3])) wraps sum parentheses (this replacement string).


please note code above works one-digit numbers. if problem, you'd use

import re  def f(m):     matched = m.group(1).strip('()').split(')(')     return '({0})'.format(sum(int(x) x in matched))  re.sub(r'((\(\d+\))+)', f, '(42)(2)2') # (44)2 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -