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

โปรแกรม Python เช็คว่า string เป็น Symmetrical หรือ Palindrome


เมื่อจำเป็นต้องตรวจสอบว่าสตริงมีความสมมาตรหรือเป็นพาลินโดรมหรือไม่ สามารถกำหนดเมธอดที่ใช้เงื่อนไข 'while' ได้ มีการกำหนดอีกวิธีหนึ่งเพื่อตรวจสอบสมมาตรที่ใช้เงื่อนไข "ในขณะที่" และ "ถ้า" ด้วย

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

ตัวอย่าง

ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -

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
  • ค่าเริ่มต้นถูกกำหนดเป็น 0 และค่าสิ้นสุดถูกกำหนดให้กับองค์ประกอบสุดท้าย
  • ตัวแปรที่ชื่อแฟล็กถูกกำหนดให้เป็น 0
  • ในขณะที่เงื่อนไขเริ่มต้น และหากองค์ประกอบเริ่มต้นและสิ้นสุดเท่ากัน ค่าเริ่มต้นจะเพิ่มขึ้น และค่าสิ้นสุดจะลดลง
  • มิฉะนั้น ตัวแปรแฟล็กถูกกำหนดให้เป็น 1 และแยกออกจากลูป
  • หากค่าของแฟล็กเป็น 0 สตริงจะเป็น palindrome ไม่เช่นนั้นจะไม่ใช่
  • มีการกำหนดวิธีการอื่นที่ชื่อว่า 'check_symmetry' ซึ่งรับสตริงเป็นพารามิเตอร์
  • ความยาวของสตริงถูกกำหนดให้กับตัวแปร
  • หากความยาวที่เหลือและ 2 ไม่ใช่ 0 ค่ากลางจะเปลี่ยนไป
  • ค่าเริ่มต้นและค่ากลางมีการเปลี่ยนแปลงอีกครั้ง
  • ใช้เงื่อนไข 'while' อื่น และค่าเริ่มต้นจะเปลี่ยนไปอีกครั้ง
  • หากค่าของแฟล็กเป็น 0 แสดงว่าสตริงนั้นสมมาตร
  • มิฉะนั้นจะไม่