-2

I'm having trouble understanding why one version of my code takes twice as long as the other. They both person the same function which is to return True if the number passed in is a palindrome, otherwise return False. The first version averages about 1.5 seconds to return True or False, while the second takes about .75 seconds on average.

1st Version: Uses a comparison:

def isPalindrome(num):
    number = str(num)
    count = 0
    for letter in number:
        if letter is number[len(number) - count - 1]:
            count += 1
    return count == len(number)

2nd version: Uses an else statement:

def isPalindrome(num):
    number = str(num)
    count = 0
    for letter in number:
        if letter is number[len(number) - count - 1]:
            count += 1
         else:
             return False
    return True
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
BigBear
  • 188
  • 10

2 Answers2

0

On a palindrome, the two functions are equivalent: They take same number n steps. If the palindrome breaks early on, 2nd function returns way earlier, while the 1st keeps incrementing the count till the string's last element.

Example:

"abcdefgh1234554321hgfedcba" -> both take n steps.
"bcdefgh1234554321hgfedcba" -> 2nd takes 1 step and return, while 1st takes n steps.
FatihAkici
  • 4,679
  • 2
  • 31
  • 48
-1

The first code version always checks all the digits, even if it knows the number can't be a palindrome.

The second code version doesn't do that.

John Gordon
  • 29,573
  • 7
  • 33
  • 58