用递归的方法很容易实现:
#coding=utf-8
def turnover(n):
if len(n) == 0:
return True
elif len(n) == 1:
return n in '018'
elif (n[0]==n[-1] and n[0] in '018') \
or n[0]+n[-1] in '969':
return turnover(n[1:-1])
else:
return False
test_cases = """0 1 6 8 9 10 11 18 69 80 88
91 96 99 100 101 111 121 619 916 6699 18181 """
for test_num in test_cases.split():
print(test_num, turnover(test_num))
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
============================ RESTART: F:\tmp\1.py ============================
0 True
1 True
6 False
8 True
9 False
10 False
11 True
18 False
69 True
80 False
88 True
91 False
96 True
99 False
100 False
101 True
111 True
121 False
619 True
916 True
6699 True
18181 True
>>>