This one was pretty simple to find the answer, though I'm not convinced it's nearly as efficient as I could be (I'd love some recommendations!). The only part that tool much thought was the function to determine if a string is a palindrome. What it does is it compare the first and last characters of the string, moving inward if they are equal. The other function just iterates all possible combinations of 2 3-digit numbers, takes their product, and stores it if it is larger than the previously stored value. I just a range that starts at the end and decrements, though it has no advantage over starting from the beginning. It goes from 999 to 99 because the 2nd value isn't inclusive, so the range really stops at 100.
As far as learning python goes, I did have to see how to iterate a list of numbers backwards, ending up with
range(start, end, step).
# val - string
def is_palindrome(val):
val = list(val)
front, end = 0, len(val) - 1
while front < end:
if val[front] == val[end]:
front += 1
end -= 1
else:
return False
return True
def solve():
vmax = -1
for i in range(999,99,-1):
for j in range(999,99,-1):
vint = i * j
if is_palindrome(str(vint)) and vint > vmax:
vmax = vint
return vmax
print 'Answer: ' + str(solve())
Here's the link to my solution: http://pastebin.com/rjaHJFsT.
ReplyDelete