Quick Overview
`s[::-1]` builds a reversed copy, so comparing it against `s` is a palindrome test in one expression. It costs `O(n)` extra memory that two pointers would avoid.
Create a function is_symmetrical(num) that takes a number and returns True if the number is symmetrical (a palindrome that reads the same backward as forward), and False otherwise.
Palindrome checks test string conversion, sequence comparison, and numerical data manipulation.
Convert the number to a string using str(), then compare it to its reversed slice s[::-1]:
def is_symmetrical(num):
s = str(num)
return s == s[::-1]
# Testing our function
print(is_symmetrical(7227)) # Output: True
print(is_symmetrical(12567)) # Output: False
print(is_symmetrical(444444)) # Output: True
print(is_symmetrical(9939)) # Output: False
str(7227) yields string "7227"."7227"[::-1] yields reversed string "7227"."7227" == "7227" evaluates to True.num[::-1]) raises a TypeError: 'int' object is not subscriptable. Always convert numbers to strings with str(num) first!Cast numbers to strings before slicing. Next, let's check if a Python dictionary is empty!
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.