# Palindromes

*By hannywillis On September 12, 2012 · Leave a Comment*

Let me start with palindromes. The word sounds familiar any time mentioned and yet far much unknown to me. Palindrome simply means words or numericals that have same meaning even if reversed e.g. Madam, 11,9009,11-9-11(dates). in this session we deal with numerical palindromes. One can easily mention the single and double digits palindromes which are only 18 in number. The trouble start for the 3,4,5 digits onwards. It took me 3 days to come up with a sage program that can be used to find the largest palindrome made from the product of two 3-digit numbers (from projecteuler). The first day with help from David and Tom, I got the clear meaning of palindrome and away to form a list from a numerical value using mathematical tools i.e. Floor, log, %, and //. the second day, i came up with a function that tests if a value is a palindrome. This was a step to reach the solution to the problem. Later in the day, i came up with a function that can produce the list of palindromes product of 3 digit numbers. On the third day, We work on making the function output the highest palindrome and the two 3-digit multiples. The function can also work with many other multiples.

Code for checking whether a number n is a palindrome

n = 1221 q = [] c = 1 y = floor(log(n,10))+1 ;print y for x in range(y): b = n//c a = b%10 q.append(a) c=(c*10) s = q[:] s.reverse() #print s,q s==qThe function forms a list, q from the number n using the 'for loop'. Copies the list q to s, then reverse the content of list s. Finally checks whether list s is equal to list q.

Defined function code(product of two 3-digit number)

def is_palindrome2(n): l1=list(str(n)) l2=l1[:] l2.reverse() return l1==l2 def biggestPalindromeProduct(nDigits): if nDigits==0: return 0 palindromelist=[] palindrometuples=[] lowerBound=10^(nDigits-1) i=10^nDigits-1 while i>lowerBound: nrange=range(10^(nDigits-1),i+1) nrange.reverse() for j in nrange: d = i*j if is_palindrome2(d): palindromelist.append(d) palindrometuples.append((i,j)) lowerBound=j break i-=1 #print palindromelist,len(palindromelist) m=max(palindromelist) print m, palindrometuples[ palindromelist.index(m) ] biggestPalindromeProduct(3)Since the highest 3-digit number is 999, the function forms a list i and j with 999 as the first values in the lists. Multiplies i and j, while checking if the product is a palindrome using the is_palindome2(). When it reaches the lower bound (100), the iteration stops. The two 3-digit numbers are stored in palindrometuples list, while the product is added in palindromelist list. Finally it prints the highest from palindromelist list and its multiples from thepalindrometuples list.