Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this simple Python script reveal the incorrect answer?

I'm again working on Project Euler, this time problem #4. The point of this script is to find the largest palindromic product of two three digit numbers. I thought it was fairly straightforward to solve, but I'm getting an answer that is too low. More specifically, I am getting 580085, and the answer is 906609.

Could someone tell me what about this is incorrect?

#!/usr/bin/env python
# encoding: utf-8
"""
P4.py

Created by Andrew Levenson on 2010-06-29.
Copyright (c) 2010 __MyCompanyName__. All rights reserved.
"""

import sys
import os


def main():
    for x in range(100, 1000):
        for y in range(100, 1000):
            z = str( x * y )
            s = str( z[::-1] ) # Reverse z
            if z == s:
                t = z
    print t


if __name__ == '__main__':
    main()
like image 368
Oso Avatar asked Jun 24 '26 09:06

Oso


1 Answers

Your code doesn't make sure it prints the largest product, since there could later be a smaller product which replaces it. To fix it, initialize t to zero, and replace your condition with

if z==s and int(z)>t:
    t = int(z)

Or equivalently,

if z==s:
    t = max(t,int(z))

Edit: Fixed int/string issues above. It's a bit cleaner to avoid the conversion to string and back to int like this though:

def isPalindrome(x):
    s = str(x)
    return s == s[::-1]

t = 0
for x in range(100, 1000):
    for y in range(100, 1000):
        z = x * y
        if isPalindrome(z) and z > t:
            t = z
print t
like image 190
interjay Avatar answered Jun 26 '26 05:06

interjay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!