【问题标题】:How to make loop calculate faster如何使循环计算更快
【发布时间】:2021-11-28 10:45:54
【问题描述】:

我想让这段代码计算得更快。我的代码有太多循环,我想减少它。如何最小化 for 循环和 while 循环。我的代码即将对英文单词进行划分,出现在字符串(String)文本中,3个字符,统计三组字符出现的频率。该函数的值为 dict,其中键是文本中三个字符的集合,值是该字符在键中出现的频率。必须是单词,如果长度小于3,频率计数不区分大小写('ant'和'Ant'是cadia)。字符必须定义为'a','in'等键。

def main():
    text = "Thank you for help me"
    print(three_letters_count(text))


def three_letters_count(text):
    d = dict()
    res = []
    li = list(text.lower().split())
    for i in li:
        if len(i) < 3:
            res.append(i)  
        while len(i) >= 3: 
            res.append(i[:3])  
            i = i[1:]
    
    for i in res:
        d[i] = res.count(i)
        
    return d
    
    



if __name__ == '__main__':
    main()

【问题讨论】:

  • 你的函数的最终目标是什么。您对此有何期待?
  • 我想让它跑得更快。
  • 我明白,但你的代码的目的是什么。在专注于代码优化之前,我希望了解您对函数的尝试。
  • 这是您的预期输出吗:{'tha': 1, 'han': 1, 'ank': 1, 'you': 1, 'for': 1, 'hel': 1 ,'elp':1,'我':1}`。 (只是运行你的代码)。你的目标?因为这里不清楚...
  • 我也希望在您的示例中使用“tin”。第一个 for 循环省去了自己解析字符串的麻烦,但代价是遍历字符串一次。可以通过从某个起始位置而不是字符串的开头切片来更改 while 循环。这样可以避免您重复复制i。如果你为你的res 使用哈希,你可以即时计算,而不是事后计算。

标签: python python-3.x for-loop while-loop nested


【解决方案1】:

正如所承诺的,只是接受答案的替代方案:

def main():
    text = "Thank you for help me thank you really so much"
    print(three_letters_count(text))


def three_letters_count(text):
    d = dict()
    res = {}
    li = list(text.lower().split())
    for i in li:
        if len(i) < 3:
            if (i in res):
                res[i] = res[i] + 1
            else:
                res[i] = 1  
        startpos = 0
        for startpos in range(0, len(i)):
            chunk = i[startpos:startpos + 3]
            if (chunk in res):
                res[chunk] = res[chunk] + 1
            else:
                res[chunk] = 1

    return res

if __name__ == '__main__':
    main()

它产生(使用修改后的输入):

{'tha': 2, 'han': 2, 'ank': 2, 'you': 2, 'for': 1, 'hel': 1, 'elp': 1, 'me': 1, 'rea': 1, 'eal': 1, 'all': 1, 'lly': 1, 'so': 1, 'muc': 1, 'uch': 1}

【讨论】:

    【解决方案2】:

    您可以调整 while 外观并将其切换为 for 循环。

    见下方调整后的功能。

    def three_letters_count(text):
        d = dict()
        res = []
        li = list(text.lower().split())
        for i in li:
            if len(i) < 3:
                res.append(i)  
            for index in range(0, len(i)):
                three_letter = i[index:index+3]
                if(len(three_letter) >= 3):
                    res.append(three_letter)
        
        for i in res:
            d[i] = res.count(i)
            
        return d
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-11
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2018-08-26
      • 2021-05-30
      相关资源
      最近更新 更多