U
U
Umid2017-07-28 21:49:52
Python
Umid, 2017-07-28 21:49:52

How can you improve the algorithm for finding the largest palindrome number in the product of two numbers?

Good evening.
I'm trying to solve a problem.
Wrote a script:

def isPolindrom(mystr):
  str_reverse = mystr[::-1]

  if str_reverse == mystr:
    # print(mystr)
    return True
  return False

def euler4():
  numbers = [ {
    "num": 99999,
    "i": 0
  } ]

  polindromHasFound = False
  polindroms = []

  while not polindromHasFound:
    nextNum = numbers[len(numbers) - 1]['num'] - 1

    for el in numbers:
      numForTest = el["num"] * (el["num"] - el["i"])
      if isPolindrom( str(numForTest) ):
        polindroms.insert( len(polindroms), numForTest )
      el["i"] += 1

    if len(polindroms) >= 100:
      print( polindroms )
      print( max(polindroms) )
    
      polindromHasFound = True

    if numbers[0]["i"] != 0:
      numbers.insert( len(numbers), {
        "num": nextNum,
        "i": 0
      } )

euler4();

How the algorithm works:
3e7a93fd2956494885f2e2b528c15a2c.jpg
Each line from the picture is a new iteration of the while loop.
The for loop finds the product of each cell, and checks it for palindrome, if it is, then the number is written to the array with the rest of the found palindromes.
The while loop runs until there are 100 palindromic numbers in the array.
Because at the time of drawing up the algorithm, I did not take into account that the numbers will not go in descending order, for example, take the first cell of the 4th line from the picture, and compare it with the first value of the fifth line: 996*996 and 999*995. This is where my mistake was, so it will not be possible to take only the first palindrome found (I already tried it, it turns out 888888, but in fact, the largest palindrome is 906609).
And that is why I made a collection of the first 100 palindromic numbers in order to select the largest from it. But, it turns out a lot of unnecessary calculations, and there is a chance that the algorithm will give me not the biggest palindrome when working, for example, with two eight-digit numbers.
How can you start multiplying so that the product is written in descending order?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2017-07-28
@Dronablo

Why do you need an array at all?

max_poly = 0
for i in range(100, 1000):
    for j in range(100, 1000):
        if i*j>max_poly and str(i*j) == str(i*j)[::-1]:
            max_poly = i*j
print(max_poly)

906609

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question