Khi cần sắp xếp các từ palindrome trong câu, ta định nghĩa phương thức nhận chuỗi, trước tiên kiểm tra palindrome. Sau đó sắp xếp tất cả từ trong chuỗi và trả về.
Ví dụ
def check_palindrome(my_string):
if my_string == my_string[::-1]:
return True
else:
return False
def print_sort_palindromes(my_sentence):
my_list = []
my_result = list(my_sentence.split())
for i in my_result:
if check_palindrome(i):
my_list.append(i)
my_list.sort()
j = 0
for i in range(len(my_result)):
if check_palindrome(my_result[i]):
my_result[i] = my_list[j]
j += 1
for i in my_result:
print(i)
my_sentence = "hi madam, how are u"
print("The sentence is")
print(my_sentence)
print("The result is:")
print_sort_palindromes(my_sentence)
Đầu ra
The sentence is hi madam, how are u The result is: hi madam, how are u
Giải thích
- Hàm
check_palindromekiểm tra chuỗi đối xứng. - Hàm
print_sort_palindromestách câu thành từ, lọc palindrome, sắp xếp, thay thế vào vị trí gốc. - Định nghĩa câu, gọi hàm, hiển thị.
- Lưu ý: Ví dụ "madam," có dấu phẩy nên không phải palindrome thuần túy. Cần tiền xử lý loại bỏ dấu câu.