Home > OS >  How to make loop calculate faster
How to make loop calculate faster

Time:10-09

I want to make this code calculate faster . My code have too much loop I want to make it less. How to minimize for loop and while loop. My code is about to Dividing English words, appearing in strings (String) text, 3 characters, and counting the frequency of three sets of characters. The function has a value of dict, where the key is a set of three characters in text, and a value is the frequency of that character in the key. Must be a word, the frequency count is Case Insensitive ('ant' and 'Ant' are cadia ) if the length is less than 3. Characters must be defined as keys such as '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()

CodePudding user response:

You could adjust your while look and switch this out for a for loop.

See the adjusted function below.

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

CodePudding user response:

As promised, just an alternative to the accepted answer:

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()

It yields (with the modified input):

{'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}
  • Related