I wrote this program as a solution to the 2015 British Informatics Olympiad question on "block" palindromes.
Brief overview of the task:
A palindrome is a word that shows the same sequence of letters when reversed.
If a word can have its letters grouped together in two or more blocks (each containing one or more adjacent letters) then it is a block palindrome if reversing the order of those blocks results in the same sequence of blocks.
For example, using brackets to indicate blocks, the following are block palindromes:
- BONBON can be grouped together as (BON)(BON);
- ONION can be grouped together as (ON)(I)(ON);
- BBACBB can be grouped together as (B)(BACB)(B) or (BB)(AC)(BB) or (B)(B)(AC)(B)(B)
Note that (BB)(AC)(B)(B) is not valid as the reverse (B)(B)(AC)(BB) shows the blocks in a different order.
TASK: Write a program which reads in a word of between 2 and 10 (inclusive) uppercase letters.
You should output a single number, the number of different ways the input can be grouped to show it is a block palindrome.
What tips do you have for improving my solution:
# theonlygusti's solution to Question 1(a)
word = input()
if not (2 <= len(word) <= 10):
print("Your input must be between 10 and 2 characters, inclusive.")
exit()
if not word.upper() == word:
print("Your input must be all uppercase, e.g. BBACBB")
exit()
if not word.isalpha():
print("Your input must contain only letters, this means characters like numbers and spaces are not allowed.")
exit()
def number_of_block_palindrome_groupings(string):
total_groupings = 0
for i in range(1, len(string)//2+1):
if (string[:i] == string[-i:]):
total_groupings += 1 + number_of_block_palindrome_groupings(string[i:-i])
return total_groupings
print(number_of_block_palindrome_groupings(word))