Add math.py script for palindrome number detection
- Add is_palindrome() function to check if a number is palindrome - Include main() function with test cases and interactive mode - Add comprehensive test cases covering various scenarios
This commit is contained in:
71
math.py
Normal file
71
math.py
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
math.py - 判断回文数的脚本
|
||||||
|
"""
|
||||||
|
|
||||||
|
def is_palindrome(n: int) -> bool:
|
||||||
|
"""
|
||||||
|
判断一个整数是否是回文数。
|
||||||
|
|
||||||
|
参数:
|
||||||
|
n: 要检查的整数
|
||||||
|
|
||||||
|
返回:
|
||||||
|
如果是回文数返回True,否则返回False
|
||||||
|
"""
|
||||||
|
if n < 0:
|
||||||
|
return False
|
||||||
|
if n == 0:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 转换为字符串并检查是否等于反转后的字符串
|
||||||
|
str_n = str(n)
|
||||||
|
return str_n == str_n[::-1]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""测试函数"""
|
||||||
|
test_cases = [
|
||||||
|
121, # True
|
||||||
|
12321, # True
|
||||||
|
123, # False
|
||||||
|
1221, # True
|
||||||
|
123321, # True
|
||||||
|
1234321, # True
|
||||||
|
12344321, # True
|
||||||
|
10, # False
|
||||||
|
0, # True
|
||||||
|
-121, # False
|
||||||
|
123456, # False
|
||||||
|
123454321,# True
|
||||||
|
]
|
||||||
|
|
||||||
|
print("测试回文数判断函数:")
|
||||||
|
print("-" * 40)
|
||||||
|
for num in test_cases:
|
||||||
|
result = is_palindrome(num)
|
||||||
|
print(f"{num:12} -> {'是回文数' if result else '不是回文数'}")
|
||||||
|
|
||||||
|
# 额外测试:用户输入
|
||||||
|
print("\n" + "=" * 40)
|
||||||
|
print("手动测试模式 (输入 'exit' 退出)")
|
||||||
|
print("=" * 40)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
user_input = input("请输入一个整数: ").strip()
|
||||||
|
if user_input.lower() == 'exit':
|
||||||
|
print("程序结束。")
|
||||||
|
break
|
||||||
|
|
||||||
|
try:
|
||||||
|
num = int(user_input)
|
||||||
|
if is_palindrome(num):
|
||||||
|
print(f"{num} 是回文数。")
|
||||||
|
else:
|
||||||
|
print(f"{num} 不是回文数。")
|
||||||
|
except ValueError:
|
||||||
|
print("错误:请输入有效的整数。")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user