Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if mirror image of a number is same if displayed in seven segment displays in Python
In seven-segment displays, only certain digits look the same when mirrored horizontally. We need to check if a number appears identical to its mirror image when displayed on such a device.
The digits that look the same when mirrored in seven-segment displays are 0, 1, and 8. Other digits like 2, 3, 4, 5, 6, 7, 9 don't have symmetric mirror images.
Understanding Seven-Segment Mirror Images
Algorithm Steps
To solve this problem, we follow these steps ?
- Convert the number to string format
- Check if all digits are mirror-symmetric (only 0, 1, 8)
- Check if the number reads the same forwards and backwards (palindrome)
- Return True only if both conditions are met
Example
Let us see the implementation to get better understanding ?
def solve(n):
num_str = str(n)
# Check if all digits are mirror-symmetric
for i in range(len(num_str)):
if num_str[i] not in ['0', '1', '8']:
return False
# Check if the number is a palindrome
left = 0
right = len(num_str) - 1
while left < right:
if num_str[left] != num_str[right]:
return False
left += 1
right -= 1
return True
# Test cases
n = 818
print(f"Input: {n}")
print(f"Output: {solve(n)}")
# Additional test cases
test_cases = [0, 1, 8, 11, 88, 101, 181, 123, 808]
print("\nAdditional test cases:")
for num in test_cases:
result = solve(num)
print(f"{num}: {result}")
Input: 818 Output: True Additional test cases: 0: True 1: True 8: True 11: True 88: True 101: True 181: True 123: False 808: True
How It Works
The solution works in two phases:
- Digit validation: We check each digit to ensure it's mirror-symmetric (0, 1, or 8)
- Palindrome check: We use two pointers to verify the number reads the same forwards and backwards
For example, 818 passes both tests ? all digits (8, 1, 8) are mirror-symmetric, and it reads the same forwards and backwards.
Alternative Approach
We can also solve this using string slicing for the palindrome check ?
def solve_alternative(n):
num_str = str(n)
# Check if all digits are mirror-symmetric
valid_digits = {'0', '1', '8'}
if not all(digit in valid_digits for digit in num_str):
return False
# Check if palindrome using slicing
return num_str == num_str[::-1]
# Test the alternative approach
n = 818
print(f"Alternative approach result: {solve_alternative(n)}")
Alternative approach result: True
Conclusion
To check if a number's mirror image is the same in seven-segment displays, verify that all digits are mirror-symmetric (0, 1, 8) and the number is a palindrome. This ensures the number appears identical when horizontally mirrored.
