疯狂的化学方程式

10

``````C6H5COOH-O2=7CO2+3H2O
``````

``````No
``````

``````2Fe(CN)6+2SO2+202=Fe2(SO4)2+6C2N2
``````

``````Yes
``````

``````2SO2=2SO4-2O2
``````

``````Yes
``````

MtnViewMark 2014年

@MtnViewMark应该是一个程序。每次运行应采用一个方程式。
gthacoder 2014年

r3mainer 2014年

@squeamishossifrage哦，是的。当然。谢谢。问题已更新。
gthacoder 2014年

2

Mathematica 152

``````f=Times@@@Tr@CoefficientRules@ToExpression@(r=StringReplace)[r[
#<>")",{"="->"-(",x:_?LetterQ|")"~~y_?DigitQ:>x<>"^"<>y}],x_?UpperCaseQ:>" "<>x]⋃{}=={0}&
``````

``````f@"C6H5COOH-O2=7CO2+3H2O"
f@"2Fe(CN)6+2SO2+2O2=Fe2(SO4)2+6C2N2"
f@"2SO2=2SO4-2O2"
``````

MtnViewMark 2014年

@MtnViewMark更精确地讲，我用计算幂，`Tr@CoefficientRules`然后用乘以系数`Times@@@`。对于`O``2*2+2*2=4*2`，为`C``2*6 = 6*2`
ybeltukov

2

Python 2.7、316 276个字符

``````import re
r=re.sub
x='(^|[=+-])'
y=r'\1+\2'
z='(\w)([A-Z(])'
t=r('=','==',r(z,y,r(z,y,r('([A-Za-z)])(\d)',r'\1*\2',r('([=+-]|\$)',r')\1',r(x+'(\d+)',r'\1\2*(',r(x+'([A-Z])',r'\1(\2',raw_input())))))))
E=re.findall('[A-Za-z]+',t)
print all(eval(t,{f:f==e for f in E})for e in E)
``````

``````(C*6+H*5+C+O+O+H)-(O*2)==7*(C+O*2)+3*(H*2+O)
2*(Fe+(C+N)*6)+2*(S+O*2)+2*(O*2)==(Fe*2+(S+O*4)*2)+6*(C*2+N*2)
2*(S+O*2)==2*(S+O*4)-2*(O*2)
``````

2

``````import Data.List
import Text.Parsec
(&)=fmap
r=return
s=string
l f b=(>>=(&b).f)
x=(=<<).replicate
m=sort&chainl1(l x(concat&many1(l(flip x)n i))n)((s"+">>r(++))<|>(s"-">>r(\\)))
i=between(s"(")(s")")m<|>(:[])&(l(:)(many lower)upper)
main=getContents>>=parseTest(l(==)(s"=">>m)m)
``````

``````& echo 'C6H5COOH-O2=7CO2+3H2O' | runhaskell Chemical.hs
False

& echo '2Fe(CN)6+2SO2+2O2=Fe2(SO4)2+6C2N2' | runhaskell Chemical.hs
True

& echo '2SO2=2SO4-2O2' | runhaskell Chemical.hs
True
``````

``````import Control.Applicative ((<\$>), (<*>))
import Data.List
import Text.Parsec
import Text.Parsec.String (Parser)

type Atom = String

{- golf'd as x -}
multiple :: Int -> [Atom] -> [Atom]
multiple n = concat . replicate n

{- golf'd as m -}
chemicals :: Parser [Atom]
chemicals = sort <\$> chainl1 molecules op
where
op :: Eq a => Parser ([a] -> [a] -> [a])
op = (char '+' >> return (++))
<|> (char '-' >> return (\\))

molecules :: Parser [Atom]
molecules = multiple <\$> number <*> terms

terms :: Parser [Atom]
terms = concat <\$> many1 term

term :: Parser [Atom]
term = flip multiple <\$> item <*> number

{- gofl'd as i -}
item :: Parser [Atom]
item = between (char '(') (char ')') chemicals
<|> (:[]) <\$> atom
where
atom :: Parser Atom
atom = (:) <\$> upper <*> many lower

{- gofl'd as n -}
number :: Parser Int
number = option 1 \$ read <\$> many1 digit

{- gofl'd as main -}
main :: IO ()
main = getContents >>= parseTest chemEquality
where
chemEquality :: Parser Bool
chemEquality = (==) <\$> chemicals <*> (char '=' >> chemicals)
``````
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.