-1

You need to get a list with all palindrome numbers in the range from 100 to 1000. This problem can be solved in two ways:

  1. Check the first and last digits of the number, and if they match, write them to the list.
palindromes = [n for n in range(100, 1000) if n // 100 == n % 10]
print(palindromes)
  1. Convert the number to a string and check it with its "inverted" copy.
palindromes = [i for i in range(100, 1001) if str(i) == str(i)[::-1]]
print(palindromes)

Question: Which of these methods is preferable (interpreted faster or takes up less PC resources) and which one is better to use?

Ghost Ops
  • 1,710
  • 2
  • 13
  • 23
vlados155
  • 56
  • 6
  • "interpreted faster or takes up less PC resources" - you can measure this using the built-in `timeit` library – ForceBru Sep 24 '21 at 13:34
  • Personally, I prefer the variable named 'n'. Besides, depending on how python the third is programmed, I'd say, nevertheless, that the integer version is likely faster and takes less ressources. – Déjà vu Sep 24 '21 at 13:35
  • I suggest reading through this Q&A to see how to time these two list comprehensions yourself: https://stackoverflow.com/questions/8220801/how-to-use-timeit-module/ - as for "which one is better to use", that is a matter of opinion so it's not a question for Stack Overflow. – kaya3 Sep 24 '21 at 13:38
  • I recently started learning Python and didn't know about timeit. Tnanks! – vlados155 Sep 24 '21 at 13:39

1 Answers1

0

Times along with another solution:

 67.6 μs  [n for n in range(100, 1000) if n // 100 == n % 10]
419.0 μs  [i for i in range(100, 1001) if str(i) == str(i)[::-1]]
 10.1 μs  [i*10 + i//10 for i in range(10, 100)]

"Resources" (memory) is minimal for all of them.

The str solution has the advantage of scaling most easily, i.e., you could for example change its range to range(100, 1000001) and it would find longer palindromes.

The non-filtering solution has the advantage of scaling best, i.e., for longer numbers the method would be even faster in comparison to the others.

My benchmark code (Try it online!):

from timeit import repeat

S = [
    '[n for n in range(100, 1000) if n // 100 == n % 10]',
    '[i for i in range(100, 1001) if str(i) == str(i)[::-1]]',
    '[i*10 + i//10 for i in range(10, 100)]',
]

for _ in range(3):
    for s in S:
        t = min(repeat(s, number=100)) / 100
        print('%5.1f μs ' % (t * 1e6), s)
    print()
no comment
  • 6,381
  • 4
  • 12
  • 30