Perform CamelCase pattern matching in Python

In this tutorial, you will learn how to do the CamelCase pattern-matching task in Python. CamelCase is a practice of writing a phrase or sentence with each new word starting with a capital letter and leaving no spaces in between.

For example :

  1. AppleScript
  2. AirPod

Let us start with our given problem statement.

Python program to perform CamelCase pattern matching

We are provided with a list of words in CamelCase notation. We are required to print all the words in the dictionary with the given pattern of upper case letters.

Example: 

Input: array[] = [ “WelcomeIndia”, “WelcomeToIndia”, “IndiaWelcomesYou” ], pattern = “WTI”

Output: WelcomeToIndia

Note: Here in the above example there is only one word matching the pattern WTI.

Implementation:

The basic idea is to take all the keys in each word one by one. Here the key is the capital letters in the original word present in the dictionary. Now search the correct match for the given pattern.

Approach:

  1. Traverse through every word and keep a record of every capital letter that is encountered in the given string.
  2. For Example:
    For string = “WelcomeIndia”

    map {
    
         {W, WelcomeIndia},
    
         {WI, WelcomeIndia},
    
    }
  3. After mapping is done for all the strings given. Search for the given pattern in the map.
  4. Print if the match is found.

 

Here is a code for the given approach :

def CamelCase(strings, pattern) : 
    map = dict.fromkeys(strings,None);  
    for i in range(len(strings)) :  
        s = "";  
        l = len(strings[i]);  
        for j in range(l) :  
            if (strings[i][j] >= 'A' and strings[i][j] <= 'Z') : 
                s += strings[i][j];  
                  
                if s not in map : 
                    map[s] = [strings[i]] 
                      
                elif map[s] is None : 
                    map[s] = [strings[i]] 
                      
                else : 
                    map[s].append(strings[i]);  
  
    wordFound = False;   
    for key,value in map.items() :  
        if (key == pattern) : 
            wordFound = True;  
            for itt in value : 
                print(itt);   
    if (not wordFound) : 
        print("No match found");  

if __name__ == "__main__" :  
  
    strings = [ 
        "Hi", "Hello", "HelloWorld",  
        "HiTech", "HiGeek", "HiTechWorld",  
        "HiTechCity", "HiTechLab"
    ];   
    pattern = "HT";   
    CamelCase(strings, pattern);

 

You may also like :

Leave a Reply

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