When you try to figure out patterns yourself, and fail to find a solution for all cases, it looks something like this:
(Python code that generates palindromes, as opposed to checking whether each natural number is a palindrome or not)
The results suggest the generating function is more than 20 times faster.
There might be a better palindrome generating algorithm here, haven't tested it though. Then again, it uses strings which are then converted to integers.
Don't do this in production or anywhere someone other than you reads the code you write.
(Python code that generates palindromes, as opposed to checking whether each natural number is a palindrome or not)
import timeit NUM = 100000 def get_palindromes(n): for i in range(1, n+1): if str(i)[::-1] == str(i): yield i def get_palindromes_2(n, s=1): while s <= n: yield s if (s / (10 ** ( len(str(s)) / 2 ))) % 10 == 0 and (len(str(s)) % 2 == 1): s += 10 ** ( len(str(s))/2 ) elif s == 9 or s == 99 or s == 999 or s == 9999 or s == 99999: s += 2 elif ((s % 10 == 9 and (s / 10) % 10 == 9)) and s / 10 ** (len(str(s))-1) != 9: s += 2 elif s / 10 == 0: s += 1 elif s / 100 == 0: s += 11 elif (s / (10 ** ( len(str(s)) / 2 ))) % 10 == 9 and (s / 10) % 10 == 9: s += 11 elif (s / (10 ** ( len(str(s)) / 2 ))) % 10 == 9: if len(str(s)) % 2 == 1: s += 11 * (10 ** (len(str(s))/2 - 1)) else: s += 11 * (10 ** ( len(str(s)) / 2 - len(str(s))/2 )) elif len(str(s)) % 2 == 1: s += 10 ** ( len(str(s))/2 ) else: s += 11 * 10 ** ( len(str(s)) - len(str(s))/2 - 1 ) if __name__ == '__main__': print "Checking for all palindromes less than %s:" % (NUM,) print timeit.timeit('list(get_palindromes(NUM))', setup='from __main__ import get_palindromes, NUM', number=10) print "Generating all palindromes less than %s" % (NUM,) print timeit.timeit('list(get_palindromes_2(NUM))', setup='from __main__ import get_palindromes_2, NUM', number=10) print "Both return same results:" print list(get_palindromes(NUM)) == list(get_palindromes_2(NUM))
The results suggest the generating function is more than 20 times faster.
Checking for all palindromes less than 100000: 0.631178268752 Generating all palindromes less than 100000 0.0270419578788 Both return same results: True [Finished in 0.8s]
There might be a better palindrome generating algorithm here, haven't tested it though. Then again, it uses strings which are then converted to integers.
Don't do this in production or anywhere someone other than you reads the code you write.
No comments:
Post a Comment