APCS Jan 2022 - h083 Q3 [Python]
Problem statement:
A fortune-stick container holds M sticks, each labeled with a string of lowercase English letters. Draw two sticks with strings S and T. If their concatenation can be split into two identical halves, the result is an auspicious answer indicating divine approval; otherwise, it indicates disapproval or no answer. For example, piep and ie form piepie, which splits into pie and pie, while foo and bar do not satisfy the condition. Interestingly, if S followed by T works, T followed by S also works: both piepie and iepiep split into identical halves. Count how many pairs among the M sticks produce an auspicious answer, counting each combination only once.
m = int(input())
c = set()
for _ in range(m):
c.add(input())
total = 0
for i in c:
for idx in range((len(i) - 1 )//2):
idx += 1
if i[:idx] == i[-idx:] and i[idx:-idx] in c:
total += 1
print(total)
Solution report
- Loop over every string
iin the set and use indexidxto check whether the two ends match. - If they match and the middle substring remaining after removing both ends is also in set
c, this is a valid pair. - Increment
totalfor each pair found. Printtotalto output the number of qualifying pairs.
Important points
- String slicing: For
abyyyab, check matching prefixes and suffixes by looping through half the string:if i[:idx] == i[-idx:]. - Searching with
set(): Store all strings in Python’s built-inset(). Checkif i[idx:-idx] in cto ensure the middle substring is also a string in the container.
Key concepts:
- Enumeration
- HASH
- SET
- [✔️] You may use the code directly if needed.
- [✔️] Please credit the source when sharing.

This article was translated from Traditional Chinese by AI. Meaning or wording may differ; please refer to the Traditional Chinese original as the authoritative version.