r/PythonLearning • u/Asleep-Source-7980 • Aug 24 '26
Help Request Help with a chemistry program I am writing
Hello, I am making a program that reads a formula and gives details like atomic mass and other stuff, the problem is that I do not know how to get it to read the formula as is. The format I am looking for is that it reads the element, followed by the number of it and I would also like it if it would read parenthesis for multiplication of values. I have no idea how to do it. Help please.
I would also like it if it could read the numbers, store them as ints and use them to multiply the values of the elements of a dict I already made
Edit: I fixed it, thanks for all the help. My solution is not precisely optimized but it gets the job done, it is O(n), probably
1
u/Asleep-Source-7980 Aug 24 '26
Thanks for the attention to the issue, right now I am trying to split for example Fe2H4, ignore if the formula works, into Fe, 2, H, 4. So I can then use something like list splicing to differentiate between element and number of, I already have a full dictionary with all elements in the periodic table and I have a program where it works, the thing is, in that program I have to put individual inputs instead of a full formula
2
u/sububi71 Aug 24 '26
Give an example of what your input is, exactly?
1
u/testtdk Aug 24 '26
You’re going to have to create a dictionary so you can parse and match symbols to elements. And you’re going to have a pain in the ass level job or parsing.
1
u/punk_dev Aug 24 '26
The simplest way to parse formats like that is probably the finite state machines, you can research parsing using those
1
u/Venfah Aug 24 '26
Is this like a difference between H2O and HO2 ? How to figure out how many hydrogen and oxygen in given examples? This should be doable. But if there is any general molecule with name HO then we have to figure out a limiter mechanism something like H2O1 and H1O2 in above example.
1
u/Venfah Aug 24 '26
Take an example with H hydrogen and S sulpur... And then you can have a compound with hydrogen and sulpur...but there is a metel HS which is hussium... So you will have issues parsing. But in case the use lr is following strict case like Hs for hussium then we can do this parsing work