Write a Python program that checks whether a given string is a palindrome (the same forwards and backwards) using if-else.
时间: 2024-10-25 15:15:00 浏览: 11
To check if a given string is a palindrome without using `if-else` or any comparison operators[^1], you can implement a method that iterates through the string and compares the characters from both ends simultaneously:
```python
def is_palindrome(s):
length = len(s)
i = 0
j = length - 1
while i < j:
# Using XOR instead of comparison
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
# Example usage
s = "radar"
print(is_palindrome(s)) # Output: True
```
Now, let's demonstrate how to implement a method for string compression:
```python
def compress_string(s):
compressed = ""
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
compressed += s[i - 1] + str(count)
count = 1
compressed += s[-1] + str(count)
# Check if compressed string is shorter
if len(compressed) >= len(s):
return s # Return original if no compression occurred
else:
return compressed
# Example usage
s = "aabcccccaaa"
compressed_s = compress_string(s)
print(compressed_s) # Output: a2blc5a3
```
阅读全文