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

โปรแกรม Python ตรวจสอบสตริงว่าเป็น Symmetrical หรือ Palindrome


เมื่อต้องการตรวจสอบว่าสตริงเป็น symmetrical หรือ palindrome สามารถกำหนดเมธอดที่ใช้เงื่อนไข 'while' อีกเมธอดหนึ่งสำหรับตรวจสอบ symmetry ใช้ 'while' และ 'if' เช่นกัน

Palindrome คือตัวเลขหรือสตริงที่อ่านจากซ้ายไปขวาหรือขวาไปซ้ายได้ค่าเดียวกัน ค่า index เหมือนกัน

ตัวอย่าง

def check_palindrome(my_str):
    mid_val = (len(my_str) - 1) // 2
    start = 0
    end = len(my_str) - 1
    flag = 0
    while start < mid_val:
        if my_str[start] == my_str[end]:
            start += 1
            end -= 1
        else:
            flag = 1
            break
    if flag == 0:
        print("The entered string is palindrome")
    else:
        print("The entered string is not palindrome")

def check_symmetry(my_str):
    n = len(my_str)
    flag = 0
    if n % 2:
        mid_val = n // 2 + 1
    else:
        mid_val = n // 2
    start_1 = 0
    start_2 = mid_val
    while start_1 < mid_val and start_2 < n:
        if my_str[start_1] == my_str[start_2]:
            start_1 = start_1 + 1
            start_2 = start_2 + 1
        else:
            flag = 1
            break
    if flag == 0:
        print("The entered string is symmetrical")
    else:
        print("The entered string is not symmetrical")

my_string = 'phphhphp'
print("The method to check a palindrome is being called...")
check_palindrome(my_string)
print("The method to check symmetry is being called...")
check_symmetry(my_string)

ผลลัพธ์

The method to check a palindrome is being called...
The entered string is palindrome
The method to check symmetry is being called...
The entered string is not symmetrical

คำอธิบาย

  • กำหนดเมธอด 'check_palindrome' รับสตริงเป็นพารามิเตอร์
  • คำนวณค่ากลางด้วยการหารเอาส่วนเต็มด้วย 2
  • กำหนดค่า start = 0 และ end = องค์ประกอบสุดท้าย
  • กำหนดตัวแปร flag = 0
  • ลูป while เริ่มต้น หากองค์ประกอบ start และ end เท่ากัน เพิ่ม start ลด end
  • มิฉะนั้น กำหนด flag = 1 และ break ออกจากลูป
  • หาก flag = 0 สตริงเป็น palindrome มิฉะนั้นไม่ใช่
  • กำหนดเมธอด 'check_symmetry' รับสตริงเป็นพารามิเตอร์
  • กำหนดความยาวสตริงให้ตัวแปร
  • หากเศษของความยาวหาร 2 ไม่ใช่ 0 เปลี่ยนค่ากลาง
  • เปลี่ยนค่า start และ mid อีกครั้ง
  • ใช้ 'while' อีกครั้ง และเปลี่ยนค่า start อีกครั้ง
  • หาก flag = 0 สตริงถือว่า symmetrical มิฉะนั้นไม่ใช่