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:
- 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)
- 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?
CodePudding user response:
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()