计算原子质量

在Python中成为新手...我想设计一个程序来计算原子质量,给定这样的分子'C14-H10-O'。

(我知道,已经创建了非常漂亮的程序,但是我想创建自己的程序,并为自己感到骄傲。)

我的代码快完成了,但是我发现了我无法解决的问题。

这是我的代码:

masas = {'H': 1.007825,'C': 12.01,'O': 15.9994,'N': 14.0067,'S': 31.972071,'P': 30.973762}
elements_list = ['H','C','O','N','S','P']

def calcula_masa_atomica(molecula):
    """
    Calcula la masa atomica de una molecula
    """
    import re
    masa = 0.0
    #Primero creamos los
    molecula = re.sub('[-]','',molecula) #Remove "-"
    molecula = (re.split('(\d+)',molecula))#split numbers and elements
    for i,ch in enumerate(molecula):
        if ch in elements_list: #If the element is in the elements_list,element_mass = masas.get(ch)# Get the mass of this element
            if molecula[i + 1].isdecimal(): #If the inmediately item is decimal
                masa += element_mass * int(molecula[i + 1])# Add the mass of this element by the number of times that element is present. In each iteration,the masses of each element will be added and stored in the mass object
            # If not,just add that element's mass to the sum.
            else:
                masa += element_mass

    return masa    

没问题的是,如果某些元素在该元素之后没有一位数字,则该分子看起来像'C14-H10-O2',但是Python会回答此错误。

IndexError:列表索引超出范围

我知道我有什么问题,但我不知道如何解决。

tankwu111 回答:计算原子质量

使用正则表达式d <- density(diamonds$carat,n = 2048) ggplot(data.frame(x = d$x,y = d$y * d$n),aes(x,y)) + geom_density(stat = "identity",fill = 'papayawhip',alpha = 0.3) + geom_point(data = modes(d),aes(y = y * d$n)) + scale_x_log10() ,您会发现分子中的所有基团,像这样

'(([A-Z])([0-9]*))'

然后遍历每个组,然后从'C14-H10-O2' > [('C14','C','14'),('H10','H','10'),('O2','O','2')] 'H2O' > [('H2','2'),('O','')] 找到质量,然后乘以数字(如果没有,则乘以atom

1

使用列表理解语法,它只是:

def calcula_masa_atomica(molecula):
    masa = 0.0
    for group,atom,nb in re.findall(r'(([A-Z])([0-9]*))',molecula):
        element_mass = masas.get(atom,0)
        masa += element_mass * int(nb or 1)
    return masa
本文链接:https://www.f2er.com/3127782.html

大家都在问