Skip to content Skip to sidebar Skip to footer

Getting Triplet Characters From Strings

Define the get_triples_dict() function which is passed a string of text as a parameter. The function first converts the parameter string to lower case and then returns a dictionary

Solution 1:

I am not going to complete your assignment for you, but below is a good start to what you need to do. I believe you can write the code that sorts the words and prints out the dictionary. Make sure to study each line and then once you get the general idea, write your own version.

def get_triples_dict(text):
    d = dict()
    text = text.lower().replace(' ', '') # set to lowercase and remove spaces
    for i in range(len(text) - 2): # stops early to prevent index out of bounds exception
        bit = text[i: i + 3] # characters in groups of 3
        if all(c.isalpha() for c in bit): # all characters must be alphabetic
            if not bit in d: # if there's no entry
                d[bit] = 0
            d[bit] += 1
    copy = d.copy() # we cannot remove items from a list we are looping over (concurrent modification exception)
    for key, value in copy.items():
        if value == 1: # remove items with counts of 1
            d.pop(key)
    return d

Post a Comment for "Getting Triplet Characters From Strings"