In this article we will solve a python question on codewars by using the Python dictionary. Our strategy here is to use the python dictionary to keep those words that have already appeared before so we will not increase the number when we see the same word again.

Below is the entire problem we need to solve.

In cryptanalysis, words patterns can be a useful tool in cracking simple ciphers.

A word pattern is a description of the patterns of letters occurring in a word, where each letter is given an integer code in order of appearance. So the first letter is given the code 0, and second is then assigned 1 if it is different to the first letter or 0 otherwise, and so on.

As an example, the word “hello” would become “”. For this task case-sensitivity is ignored, so “hello”, “helLo” and “heLlo” will all return the same word pattern.

Your task is to return the word pattern for a given word. All words provided will be non-empty strings of alphabetic characters only, i.e. matching the regex “[a-zA-Z]+”.

Here is the solution to the above problem.

def word_pattern(word):
    word_list = list(word)
    first = False
    crypto_str = ""
    increment = 0
    word_dict = dict() # create an empty dictionary to keep increment number
    for char in word_list:
        char = char.lower() # change all characters to lower case first before make the comparison
        if not first:

            first = True
            crypto_str += str(increment)
            word_dict[char] = increment

            if char in word_dict:
                crypto_str += "." + str(word_dict[char])
                increment += 1
                crypto_str += "." + str(increment)
                word_dict[char] = increment

    return crypto_str

As you can see from above, we will assign 0 to the first character in the string and increase the decimal number each time we see a different word, but if the word has already appeared before then we will use back the same decimal number. All these are made possible with help from the Python dictionary object.

Do you have a better solution? Leave your own solution in the comment box below this post.

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *