我的方法:用字典创建一个旋转函数
# my method
def func_rotate( s ): # the funtion to rotate a valid digit
switcher ={ # dic like c: switch,case
0:0,
1:1,
2:5,
5:2,
6:9,
8:8,
9:6,
}
return switcher.get(s, "invalid")
while True:
n = int(input("please enter a positive integer:"))
count = 0
if n > 0:
for i in range(1, n+1): # every integer from 1 to n(include n)
lst_number = []
rot_lst_number = []
valid_condition = True
for j in str(i): # put every digit into a list
lst_number.append(int(j))
for k in lst_number:
if func_rotate( k ) == "invalid":
valid_condition = False
break
if valid_condition:
rot_lst_number.append(func_rotate( k ))
if valid_condition: # if the number doesn't include invalid digit
if rot_lst_number != lst_number:
count += 1
print("from 1 to {} have {} good numbers".format(n, count))
else:
print("please enter a positive integer")
老师的方法:
如果出现3,4,7就不是goodnumber了,如果出现2,5,6,9就一定是goodnumber
invalid_digits = [3, 4, 7]
valid_digits = [2, 5, 6, 9]
count = 0
N = input()
for x in range(1, N+1):
valid = True
valid_digits_exist = False
while x > 0:
digit = x % 10
x //= 10
# digit
if digit in invalid_digits:
valid = False
break
if digit in valid_digits:
valid_digits_exist = True
if not valid:
continue
if not valid_digits_exist:
continue
if valid_digits_exist:
count += 1