Python 练习题之一回文数
题目:求大于10的,10进制,8进制,2进制表示的回文数都一样的最小的整数。(题目来源程序员的算法趣题)
回文数:将某个数字的每个位的数字反向排列形成的新数和原来的数一样的数,例如9,例如12355321等。
直接出代码:
import numpy as np import datetime def calintnum_10(num): allnum=[] upvalue=num%10 allnum.append(upvalue) num=int(num/10) while(num!=0): allnum.append(num%10) num=int(num/10) return allnum def calintnum_8(num): allnum=[] upvalue=(num)%8 allnum.append(upvalue) num=eval(oct(int((num)/8))) while(num!=0): allnum.append((num)%8) num=eval(oct(int((num)/8))) return allnum def calintnum_2(num): allnum=[] upvalue=num%2 allnum.append(upvalue) num=eval(oct(int((num)/2))) while(num!=0): allnum.append((num)%2) num=eval(oct(int((num)/2))) return allnum def judgesuitnum(allnum_ori): allnum_rev=allnum_ori.copy() allnum_rev.reverse() if(allnum_ori==allnum_rev): return True else: return False def judgesuitnum3(num): num_8=oct(num) num_2=bin(num) all_10=calintnum_10(num) all_8=calintnum_8(eval(num_8)) all_2=calintnum_2(eval(num_2)) if(judgesuitnum(all_10) and judgesuitnum(all_8) and judgesuitnum(all_2)): return True else: return False start = datetime.datetime.now() find=False num=10 while(not find): find=judgesuitnum3(num) if(find): break else: num=num+1 end=datetime.datetime.now() spendtime=end-start print("find num is:%d"%num) print("find Spend time:{}".format(spendtime)) def strcode(num,cut=True): numstr=str(num) if(cut): numstr=numstr[2:] numstr_inv=numstr[::-1] return [numstr,numstr_inv] def judgesuitnum3_2(num): num_10str=strcode(num,False) num_8=oct(num) num_8str=strcode(num_8) num_2=bin(num) num_2str=strcode(num_2) if(num_10str[0]==num_10str[1] and num_8str[0]==num_8str[1] and num_2str[0]==num_2str[1]): return True else: return False print("******************************************") start = datetime.datetime.now() find=False num=10 while(not find): find=judgesuitnum3_2(num) if(find): break else: num=num+1 end=datetime.datetime.now() spendtime=end-start print("find num is:%d"%num) print("find Spend time:{}".format(spendtime))
一共两个方法,写的low,新学的。结果如下:明显第二种方法快了好多。
欢迎交流。