Revision befad0d9-3069-4c5a-8825-af071aab51a0 - Code Golf Stack Exchange

#Python (337 chars)

 import re
 def s(i):
 a,d,o,e=[],{},"",len(i)-1
 for b in i:a.append(dict(re.findall(r"([A-Z][a-z]*)(\d*)",b)))
 a=[{b:int(c[b])if c[b]else 1for b in c}for c in a]
 for b in a:
 for c in b:d[c]=c in d and d[c]+b[c]or b[c] 
 if"H"not in b:d["-"]=0
 d["H"]-=2*e;d["O"]-=e
 for b in d:o+=b+(str(d[b])if d[b]-1else"")if d[b]else""
 return o
The function `s(i)` takes an array of strings as an argument and outputs the result. Here is an example of a program:

 import re
 def s(i):
 a,d,o,e=[],{},"",len(i)-1 #vars b and c are used for iterating, and are not defined here
 for b in i:a.append(dict(re.findall(r"([A-Z][a-z]*)(\d*)",b))) #convert each molecule from string to a dictionary and store into a
 a=[{b:int(c[b])if c[b]else 1for b in c}for c in a] #convert all "subscripts" in a to ints, making empty strings into 1s
 for b in a:
 for c in b:d[c]=c in d and d[c]+b[c]or b[c] #add key/value pairs of array of dictionaries a to dictionary d
 if"H"not in b:d["-"]=0 #check that all molecules have at least one H(ydrogen)
 d["H"]-=2*e;d["O"]-=e #remove H(ydrogen) and O(xygen)
 for b in d:o+=b+(str(d[b])if d[b]-1else"")if d[b]else"" #convert dictionary d into output string o
 return o #return o

 inmol = ["C6H12O6","C6H12O6","C6H12O6","C6H12O6","C6H12O6","C6H12O6"]
 print(s(inmol)) #print output

AltStyle によって変換されたページ (->オリジナル) /