Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python สำหรับค้นหาสตริงย่อย Anagram


ในบทความนี้ เราจะเรียนรู้เกี่ยวกับวิธีแก้ปัญหาตามที่ระบุด้านล่าง

คำชี้แจงปัญหา − เมื่อได้รับข้อความและรูปแบบ เราจำเป็นต้องพิมพ์รูปแบบที่เกิดขึ้นทั้งหมดและการเรียงสับเปลี่ยน (หรือแอนนาแกรม) ในรูปแบบข้อความ

ทีนี้มาดูวิธีแก้ปัญหาในการใช้งานด้านล่าง -

ตัวอย่าง

# maximum value
MAX = 300
# compare
def compare(arr1, arr2):
   for i in range(MAX):
      if arr1[i] != arr2[i]:
         return False
   return True
# search
def search(pat, txt):
   M = len(pat)
   N = len(txt)
   # countP pattern account
   # countTW text window count
   countP = [0]*MAX
   countTW = [0]*MAX
   for i in range(M):
      (countP[ord(pat[i]) ]) += 1
      (countTW[ord(txt[i]) ]) += 1
   # Traversal
   for i in range(M, N):
      # Compare current window and patten counts
      if compare(countP, countTW):
         print("Found at Index", (i-M))
      # Add charcter to window
      (countTW[ ord(txt[i]) ]) += 1
      # remove charcter from window
      (countTW[ ord(txt[i-M]) ]) -= 1
   # Check for the last window
   if compare(countP, countTW):
      print("It is Found at Index : ", N-M)
# main
txt = "TUTORIALSPOINT"
pat = "TOR"
search(pat, txt)

ผลลัพธ์

Found at Index 2

โปรแกรม Python สำหรับค้นหาสตริงย่อย Anagram

ตัวแปรทั้งหมดได้รับการประกาศในขอบเขตท้องถิ่นและการอ้างอิงของตัวแปรนั้นดูได้จากรูปด้านบน

บทสรุป

ในบทความนี้ เราได้เรียนรู้เกี่ยวกับวิธีการสร้าง Python Program สำหรับ Anagram Substring Search