Question : Python: working with molecules

Dear experts,

I have also been asked to take up a small science project, working with molecules. As I am getting familiar with python, I decided i could do this too. I have several questions, please help me out as much as you can:)

1) for example, the user enters a molecule. I want python to return a list of strings where the elements of the list are the atoms from the molecule..this is like the code i got previously, but I dont know how it would do that..like if the molecule of water, which is H2O is two hydrogen (H) atoms and one oxygen (O) atom. I want python to show the atoms separately, like H and O.. how is that possible?

2) Like the question above, i want my program to return the amount of each atom the molecule contains, so it should return a list of strings where the elements of the list are the quantities of each atom from the molecule, in order..I believe i can call a module from the previous work, but i'm not sure? And what if i wanted to calculate the number of all the atoms in the molecule? Like the sum..I'm making a program for science students, a small one, i want to know how efficient python can be..

3) i wanted to make a program that calculates the atomic mass. So if there was a 2 element molecule, like H2O and python were to calculate the mass? or return it with the decimals, how would that be possible??

4) What about the molecular mass? If we had a list where each element contains an atom  and its atomic mass, how could i return the molecular mass of the molecule? Assuming that all the atoms in the molecule are also present in the list of atomic masses.. (For example, the atomic masses of H and O are 1.008 and 16.00.., so the molecular mass of H2O is supposed to be 1.008*2 + 16.00 = 18.016)

Answer : Python: working with molecules

Something along this lines:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
import re
 
weight = dict(
  H=1.008,
  O=16,
  #...
)
 
def split(mo):
  "split molecule formula 'H2O' to atoms [('H', '2'), ('O', '')]
  atoms = re.findall('([A-Z][a-z]?)(\d*)', mo)
 
def mass(atoms):
  return sum(weight[atom]*(count and int(count) or 1) for atom,count in atoms)
Open in New Window Select All
Random Solutions  
 
programming4us programming4us