เมื่อจำเป็นต้องตรวจสอบลำดับของอักขระในสตริง สามารถใช้เมธอด 'OrderedDict' ได้
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ตัวอย่าง
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)) ผลลัพธ์
The string is Hi Mark The input pattern is Ma The order of pattern is correct
คำอธิบาย
-
แพ็คเกจที่จำเป็นจะถูกนำเข้า
-
มีการกำหนดเมธอดที่ชื่อว่า 'check_order' ซึ่งรับพารามิเตอร์สองตัว
-
พจนานุกรมที่เรียงลำดับถูกสร้างขึ้นโดยใช้วิธี 'fromkeys'
-
ความยาวของรูปแบบเริ่มต้นเป็น 0
-
หากคีย์เท่ากับรูปแบบ ความยาวของรูปแบบจะเพิ่มขึ้น
-
หากความยาวของลวดลายเท่ากับความยาวปัจจุบัน แสดงว่าลำดับถูกต้อง มิฉะนั้น ลำดับจะไม่ถูกต้อง
-
ข้อความที่เกี่ยวข้องจะแสดงเป็นเอาต์พุตบนคอนโซล