I've just written a palindrome generator and would like to know what you think about it.
Especially:
- code style
- Is it possible to get the same result without making a special case for 1-digit palindromes?
- efficiency
#!/usr/bin/env python
def getPalindrome():
"""
Generator for palindromes.
Generates palindromes, starting with 0.
A palindrome is a number which reads the same in both directions.
"""
# First print all one-digit palindromes
for i in range(10):
yield i
length = 2
while True:
# Do the symmetric part
for i in range(10**(length//2-1), 10**(length//2)):
a = str(i)
r = a + a[::-1]
yield int(r)
length += 1
# Do the unsymmetric part
exponent = (length-1)//2
for prefix in range(10**(exponent-1), 10**exponent):
prefix = str(prefix)
for i in range(10):
result = prefix + str(i) + prefix[::-1]
yield int(result)
length += 1
if __name__ == "__main__":
palindromGenerator = getPalindrome()
for i, palindromeNumber in enumerate(palindromGenerator):
print("%i-th palindrome: %i" % (i, palindromeNumber))
if i >= 500:
break