Message Boards Message Boards

0
|
9473 Views
|
4 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Finding the molar mass of a compound.

Posted 10 years ago
POSTED BY: Seokin Yeh
4 Replies

Just noticed that ElementData[] can be called with element's number, hence you can consider input of the form $ X_n^m Y_k^l \dots $

Clear[A] ;
A[arg_] := Inner[Times, ElementData[#, "AtomicMass"] & /@ #1, #2, Plus] & @@ 
    Transpose@(List @@ (arg) /. {\!\(\*SubsuperscriptBox[\(x_\), \(z_\), \(y_\)] -> \({y, z}\)\), Subscript[x_, z_] -> {1, z}, x_^y_ -> {y, 1}});
A[\!\(\*SubsuperscriptBox[\(C\), \(4\), \(6\)]\ \*SubsuperscriptBox[\(H\), \(10\), \(1\)]\)]

I.M.

POSTED BY: Ivan Morozov
POSTED BY: Seokin Yeh

Hi, Seokin,

Not sure that this can be considered as an improvement of your code, but here is my solution:

A = Inner[Times, ElementData[#, "AtomicMass"] & /@ #1, #2, Plus] &  ;
A[{"Carbon", "Hydrogen"}, {4, 10}]

As for fancy user input, you can try something similar to the following:

c = "Carbon" ;
h = "Hydrogen" ;
arg = Transpose@Partition[#, 2] & @ (ToExpression[#] & /@ StringSplit["c 4 h 10"]) ;
A @@ arg

and the final version:

A = Inner[Times, ElementData[#, "AtomicMass"] & /@ #1, #2, Plus] & @@ (
        Transpose@Partition[#, 2] & @ (ToExpression[#] & /@ 
        StringSplit[#])
     )  & ;
A["c 4 h 10"]

Also Characters[] function can be used to form input arg without blanks, but it will split 10 into 1 and 0 :

Characters["c4h10"]

I.M.

POSTED BY: Ivan Morozov
POSTED BY: David Reiss
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract