Chemistry calculator in Python | Sololearn: Learn to code for FREE!
+ 2

Chemistry calculator in Python

How to convert chem. formula into math. formula? E.g.: C6H12O6 --> C*6 + H*12 + O*6

31st Oct 2019, 11:53 AM
Alexander Koval🇧🇾
Alexander Koval🇧🇾 - avatar
3 ответов
+ 3
Thank you, Vijay and Qasem! I planned to use regexps. But there is no need to import re.
31st Oct 2019, 3:08 PM
Alexander Koval🇧🇾
Alexander Koval🇧🇾 - avatar
+ 1
You can traverse whole string and whenever you get integer(character from 0-9) insert '*' at that position ( in a new string), when you switch integer to char insert '+' For example- when you traverse given string "C7H12O6", first you will encounter 'C' so append this into new string, after that you will encounter '6' that is an integer( digit from 0 to 9) So you will first append '*' and after that append '6'. After this you will get 'H' ( switch from digit to char) here append '+' and after it append 'H'. Keep going this way until you reach at the end of string. In this way you will get a new string "C*6+H*12+O*6". Note- Here all things are in string form not in integer because string-integer doesn't support arithmetic (mathematical) operations.
31st Oct 2019, 12:29 PM
Vijay Meena