【问题标题】:Count the number letter occurrences in a string计算字符串中出现的数字字母
【发布时间】:2022-01-07 01:51:55
【问题描述】:

我想在 python 中编写分子式(字符串)中原子数的摘要。字符串是一个字母后跟一个数字(当没有数字时,它被计为一个)。

输入:C3H7NO2C3H7NO2S 输出:C6H14N2O4S

我仅有的字母是:O、C、N、H 和 S。

【问题讨论】:

  • 您使用什么语言或工具?
  • 找到第一个字母 (C),检查它旁边是否有一个数字(是的,3) - 所以记住 C 和 3。重复下一个数字。当元素后面没有数字时(如 N),它的计数为 1。当你得到另一个 C 时,添加到前一个计数。现在用您选择的语言编写代码
  • 我已经添加了所需的语言作为标签 - 这样你就可以吸引正确的人

标签: python string count digits


【解决方案1】:

一个你肯定不能作为家庭作业解决方案发送的 C#“oneliner”:

var s = "C3H7NO2C3H7NO2S";
var s2 = string.Join(" ",Regex.Split(s, @"([A-Z]\d*)")
        .Where(x => !string.IsNullOrEmpty(x))
        .Select(x => Regex.Match(x, @"([A-Z])(\d*)"))
        .Select(m => new {elt = m.Groups[1].Value, cnt = m.Groups.Count > 2 ? m.Groups[2].Value : "1"})
        .Select(e => new {e.elt, cnt = string.IsNullOrEmpty(e.cnt) ? 1 : int.Parse(e.cnt)})
        .GroupBy(e => e.elt)
        .Select(g => $"{g.Key}{g.Sum(x=>x.cnt)}")
        );

// s2 contains "C6 H14 N2 O4 S1"

fiddle

  • 首先获取元素计数对(其中计数是可选的)
  • 然后将它们拆分为元素和计数(缺少计数 = 1)
  • 然后按元素分组并对计数求和
  • 然后加入一个字符串

【讨论】:

    【解决方案2】:

    def 转换(aa_seq):

    temp = re.findall('\d+|\D+', str_atoms) #split string to numbers and chars
    #print(temp)
    
    # dictionary
    dicta = {}
    
    # list to dictionary
    for i in range(int(0.5 * len(temp))):
        key = temp[2 * i] # set atom as key
        val = int(temp[2 * i + 1]) #set value as the number that follows
        # print(key + ' = ' + str(val))
        if (key in dicta): #add value to existing key
            dicta[key] += val
        else: # if key does not exist create this
            dicta[key] = val
    print(dicta)
    
    # dictionary to string
    final_str = ''
    for x in dicta:
        final_str += x + str(dicta[x])
    print(str_atoms)
    print(final_str)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-05
      • 2013-11-04
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 2021-06-11
      • 2015-12-01
      相关资源
      最近更新 更多