1
import math

thevalue = 0

for x in range (100,999):
    for y in range (100,999):
        mynum=x*y
        mynum_str=str(mynum)

        for z in range(0,math.floor(len(mynum_str)/2)):
            if mynum_str[0+z] != mynum_str[len(mynum_str)-1-z]:
                break
            else:
                if (len(mynum_str)-1-z) -1 == z:              
                    thevalue = mynum

print(thevalue)

gives me 580085 which is not the correct answer(suppose to be over 900000)... Working on http://projecteuler.net/problem=4 ... on tips on where I went wrong?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Brian
  • 151
  • 2
  • 9
  • 2
    possible duplicate of [Euler problem number #4](http://stackoverflow.com/questions/555009/euler-problem-number-4) – Paul Hankin Jan 23 '14 at 20:49
  • 2
    if you're looking for the *largest* palindromic product of two three-digit numbers, why are you starting at `100*100`? Don't you think you should work backwards from `999*999`? – roippi Jan 23 '14 at 20:50
  • good call, i'll fix that. – Brian Jan 23 '14 at 20:52
  • 2
    Note that overwriting `thevalue` as you go will not necessarily return the largest value! Imagine finding `98*50` is a palindrome, and then calculating `99*1` is a palindrome. Wouldn't it overwrite it with the smaller value? Consider adding a check to see if the current number is greater than the previous palindrome. – kevinsa5 Jan 23 '14 at 20:54
  • Thank you so much, that was my problem! – Brian Jan 23 '14 at 20:58

2 Answers2

7

You don't need an overcomplicated loop to check for the palindromic nature of the number:

# Using extended slice notation to reverse the string
if str(n) == str(n)[::-1]:
    print "Palindrome!"

As for a complete solution, your program is just looking for a palindromic number. There's more than one palindromic number that's the product of 3 digits. You want the biggest of those.

(of course, this isn't the complete solution -- but it'd be no fun if we just gave you the solution to a project Euler challenge ;) )

Max Noel
  • 8,810
  • 1
  • 27
  • 35
0

There is an easier way to check for a palindrome. Just reverse your string and compare it to the original: if(mynum_str == mynum_str[::-1])

The reason you get 580085 is that your program only prints out the last value that it finds. (There are 2470 possible palindromes.) Try either storing them in a list and sorting it, or just keeping the max version:

import math
import string

maxpalindrome = 0
for x in range (100,999):
    for y in range (100,999):
        mynum=x*y
        mynum_str=str(mynum)

        if(mynum_str == mynum_str[::-1]):
            maxpalindrome = max(string.atoi(mynum_str), maxpalindrome)

print(maxpalindrome)
Kevin
  • 2,112
  • 14
  • 15