Search code examples
pythonlistpalindrome

python - print squares of numbers which are palindromes : improve efficiency


I have an assignment to do. The problem is something like this. You give a number, say x. The program calculates the square of the numbers starting from 1 and prints it only if it's a palindrome. The program continues to print such numbers till it reaches the number x provided by you.

I have solved the problem. It works fine for uptil x = 10000000. Works fine as in executes in a reasonable amount of time. I want to improve upon the efficiency of my code. I am open to changing the entire code, if required. My aim is to make a program that could execute 10^20 within around 5 mins.

limit = int(input("Enter a number"))
def palindrome(limit):
 count = 1
 base = 1 
 while count < limit:
  base = base * base #square the number
  base = list(str(base)) #convert the number into a list of strings
  rbase = base[:] #make a copy of the number
  rbase.reverse() #reverse this copy
  if len(base) > 1: 
   i = 0
   flag = 1 
   while i < len(base) and flag == 1:
    if base[i] == rbase[i]: #compare the values at the indices
     flag = 1
    else:
     flag = 0
    i += 1
   if flag == 1:
    print(''.join(base)) #print if values match
 base = ''.join(base)
 base = int(base)
 base = count + 1
 count = count + 1
palindrome(limit)

Solution

  • He're my version:

    import sys
    
    def palindrome(limit):
        for i in range(limit):
            istring = str(i*i)
            if istring == istring[::-1]:
                print(istring,end=" ")
        print()
    
    palindrome(int(sys.argv[1]))
    

    Timings for your version on my machine:

    pu@pumbair: ~/Projects/Stackexchange  time python3 palin1.py 100000
    121 484 676 10201 12321 14641 40804 44944 69696 94249 698896 1002001 1234321 
    4008004 5221225 6948496 100020001 102030201 104060401 121242121 123454321 125686521
    400080004 404090404 522808225 617323716 942060249
    
    real    0m0.457s
    user    0m0.437s
    sys     0m0.012s
    

    and for mine:

    pu@pumbair: ~/Projects/Stackexchange  time python3 palin2.py 100000
    0 1 4 9 
    121 484 676 10201 12321 14641 40804 44944 69696 94249 698896 1002001 1234321 
    4008004 5221225 6948496 100020001 102030201 104060401 121242121 123454321 125686521
    400080004 404090404 522808225 617323716 942060249
    
    real    0m0.122s
    user    0m0.104s
    sys     0m0.010s
    

    BTW, my version gives more results (0, 1, 4, 9).