Check order of character in string using OrderedDict( ) in Python


When it is required to check the order of the character in the string, the ‘OrderedDict’ method can be used.

Below is the demonstration of the same −

Example

 Live Demo

from collections import OrderedDict
def check_order(my_input, my_pattern):
   my_dict = OrderedDict.fromkeys(my_input)
   pattern_length = 0
   for key,value in my_dict.items():
      if (key == my_pattern[pattern_length]):
         pattern_length = pattern_length + 1

      if (pattern_length == (len(my_pattern))):
         return 'The order of pattern is correct'

   return 'The order of pattern is incorrect'

my_input = 'Hi Mark'
input_pattern = 'Ma'
print("The string is ")
print(my_input)
print("The input pattern is ")
print(input_pattern)
print(check_order(my_input,input_pattern))

Output

The string is
Hi Mark
The input pattern is
Ma
The order of pattern is correct

Explanation

  • The required packages are imported.

  • A method named ‘check_order’ is defined, that takes two parameters.

  • An ordered dictionary is created using the ‘fromkeys’ method.

  • The length of pattern is initialized to 0.

  • If the key is equal to the pattern, then the length of pattern is incremented.

  • If the length of pattern is same as the current length, it means the order is right, else the order is wrong.

  • Relevant messages are displayed as output on the console.

Updated on: 17-Apr-2021

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements