Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using Python Heard recently on CarTalk: “I was driving on the highway the other

ID: 3823870 • Letter: U

Question

Using Python

Heard recently on CarTalk: “I was driving on the highway the other day and I happened to notice my odometer. Like most odometers, it shows six digits, in whole miles only. So, if my car had 300,000 miles, for example, I’d see 3-0-0-0-0-0. “

“Now, what I saw that day was very interesting. I noticed that the last 4 digits were palindromic; that is, they read the same forward as backward. For example, 5-4-4-5 is a palindrome, so my odometer could have read 3-1-5-4-4-5.”

“One mile later, the last 5 numbers were palindromic. For example, it could have read 3-6-5-4-5-6. One mile after that, the middle 4 out of 6 numbers were palindromic. And you ready for this?

“The question is, what was on the odometer when I first looked?”

Your task: Write a Python program that tests all six-digit numbers and prints any numbers that satisfy these requirements.

Explanation / Answer

Python 2.7 code:

def ispalindrom(s):
   l = len(s) - 1;
   for i in range(0,len(s)/2):
       if(s[i] == s[l]):
           pass
       else:
           return False
       l = l-1;
   return True

for i in range(100000,999999):
   n1 = i
   n2 = i + 1
   n3 = i+ 2
   s1 = str(n1)[2:6]
   s2 = str(n2)[1:6]
   s3 = str(n3)[1:5]
   if(ispalindrom(s1) and ispalindrom(s2) and ispalindrom(s3)):
       print i

Output:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote