String, variable ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • iqgrisskinka
    New Member
    • Aug 2010
    • 2

    String, variable ?

    Hello

    I'm trying to make a chemistry-program that's going to calculate the mass of an group of atoms.

    It is however hard to make it work. First I give C a value of 12 and O a value of 6. To this point everything is fine, but now I want to be able to write CO2 and have the program understand that it's supposed to take the value of C and add it to the value of O times two.

    Do you have any idea on how I should do?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    My suggestion is to write a function that would parse your chemical designations and return the total. Let's assume a notation like "C.0^2" where "." is a delimiter for the elements and "^" is a delimiter for the atom quantity of the previous element.

    Example:
    Code:
    def molecule_mass(molecule):
        massDict = {"C": 12, "O": 16, "Ca": 40, "Uut": 284}
        mass = 0
        elementList = molecule.split(".")
        for item in elementList:
            if "^" in item:
                atom, n = item.split("^")
                mass += massDict[atom] * int(n)
            else:
                mass += massDict[item]
        return mass
    
    
    print molecule_mass("C.O^2.Ca")
    The above prints "84".

    Comment

    • iqgrisskinka
      New Member
      • Aug 2010
      • 2

      #3
      Bad

      Well, there's no input... It just gives you the answer 84

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        I am assuming you have some basic level of Python knowledge. It is not appropriate for me to write a complete solution for you.

        Comment

        Working...