1

So I'm kind of new to Python. Right now I'm making a chemical equation balancer and I've got stuck because what I want to do right now is that if you receive a compound in parenthesis, with a subindex outside (like this: (NaCl)2), I want to expand it to this form: Na2Cl2 (and also get rid of the parenthesis). Right now I've managed just to get rid of the parenthesis with this code:

import string
import re

linealEquation = ""

def linealEq(equation):
    #missing code
    allow = string.letters + string.digits + '+' + '-' + '>'
    linealEquation = re.sub('[^%s]' % allow, '', equation)
    print linealEquation

linealEq("(CrNa)2 -> Cr+Na")

But how can I trace the string and multiply the indexes out of the parenthesis?

I know how to iterate over a string, but I cannot think of how to specifically multiply the sub index.

Thanks for the help.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
brolius
  • 23
  • 1
  • 7

1 Answers1

2

Probably not the shortest solution and won't work in all cases, but works for your example:

left,  right = equation.split('->')
exp = left.strip()[-1]
inside = left[1:-3]
c2 = re.findall('[A-Z][^A-Z]*', inside)
l = [s + exp for s in c2]
res =''.join(l)

N.B. you can add print statements to better understand each step...

Eric Levieil
  • 3,554
  • 2
  • 13
  • 18
  • mmm. yeah I see what you did. As you say it doesn't work for all cases, but I think now I have a better clue of what can I do. Thanks man! – brolius Apr 11 '15 at 18:39