Signup/Sign In

Python program to Check order of character in string

In this tutorial, we will learn to write a Python program to check the order of characters in a string. Strings in Python are data types for storing a sequence of characters. For a given string and a pattern, we have to check if the characters in the string follow the same sequence as the characters in the pattern or not.

Let us look at the sample input and output of the program.

Input:

string="My first"

pattern=" ys"

Output: True

Explanation: because according to the pattern 'y' should occur before 's' in the string.

To execute this task, we can use the OrderedDict() method. First, we have to create an OrderedDict for the given string where each character will be key. Declare a pointer variable for the start of the pattern and set it at 0. Then we will match the key (character of the string) with the character in the pattern. If key and character match with each other then we will increase the counter by 1. If the pointer reaches the end that means the string follows the order of the pattern. Else, the string does not follow the pattern.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Import OrderedDict from collections

Step 2- Define a function that will match the pattern and accept the string and pattern

Step 3- Declare an OrderedDict dictionary of the characters in the string

Step 4- Declare a pointer variable for the pattern and set it to 0

Step 5- Traverse the string along with the pattern

Step 6- If the character is matched increase the pointer by 1

Step 7- At the end of the loop check if the pointer variable has the same count as the length of the pattern and return "True" if the condition is satisfied

Step 8- If there is any mismatch of characters return "False"

Step 9- Initialise the string and the pattern

Step 10- Call the function and print the value

Python Program

Look at the program to understand the implementation of the above-mentioned approach. To find the length of the pattern string, we have used the len() function which is a built-in method of the String class in Python and returns the length of a string.

from collections import OrderedDict 
def checkOrder(string, pattern): 
    dic = OrderedDict.fromkeys(string) 
    ptr = 0
    for key,value in dic.items(): 
        if (key == pattern[ptr]): 
            ptr = ptr + 1
        if (ptr == (len(pattern))): 
            return 'True'
    return 'False'

string = 'Study tonight'
pattern = 'stu'
print (checkOrder(string,pattern))

string2= 'Welcome'
pattern2= 'cm'
print (checkOrder(string2,pattern2)) 


False
True

Conclusion

In this tutorial, we have seen how to check the order of a character in a string when the string and the pattern are already given. We have used the OrderedDict method to execute this task in Python.