Computer >> Máy Tính >  >> Lập trình >> Python

Kiểm tra thứ tự của ký tự trong chuỗi bằng OrderedDict () trong Python

Khi cần kiểm tra thứ tự của ký tự trong chuỗi, phương thức ‘OrderedDict’ có thể được sử dụng.

Dưới đây là minh chứng về điều tương tự -

Ví dụ

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))

Đầu ra

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

Giải thích

  • Các gói bắt buộc được nhập.

  • Một phương thức có tên ‘check_order’ được xác định, có hai tham số.

  • Một từ điển có thứ tự được tạo bằng phương thức "fromkeys".

  • Độ dài của mẫu được khởi tạo bằng 0.

  • Nếu phím bằng với mẫu thì độ dài của mẫu sẽ tăng lên.

  • Nếu độ dài của mẫu bằng với độ dài hiện tại, điều đó có nghĩa là đơn đặt hàng đúng, nếu không, đơn đặt hàng sai.

  • Các thông báo liên quan được hiển thị dưới dạng đầu ra trên bảng điều khiển.