t1=time() def main(): n=6 for a in xrange(1,10): for b in xrange(10): for c in xrange(10): for d in xrange(10): for e in xrange(10): for f in xrange(10): num=100000*a+10000*b+1000*c+100*d+10*e+f if num==a**n+b**n+c**n+d**n+e**n+f**n: print num main() print time()-t1
def cmp_nar(n): ''' n is the number of digits ''' min_num = 10**(n-1) max_num = 10**n result = [] for num in range(min_num,max_num): if num==sum([int(x)**n for x in str(num)]): result.append(num) return result
# test 3-digits print cmp_nar(3)
[解决办法] 分为两步:1. 生成所有的组合(用递归)和 2. 检测这些组合。
walker4是一个第一步,test_walker是第二步。
In [422]: def walker4(n, power_table): ...: if n == 1: ...: for d in range(1, 10): ...: yield d, power_table[d] ...: else: ...: for k, s in walker4(n-1, power_table): ...: for d in range(1,10): ...: yield k*10 + d, s + power_table[d]
In [423]: def test_walker(n, walker): ...: power_table = [pow(d, n) for d in range(10)] ...: return [k for k, v in walker(n, power_table) if k == v]
In [424]: test_walker(6, walker4) Out[424]: [548834]
In [425]: test_walker(7, walker4) Out[425]: [1741725, 9926315]
def walker4(n, power_table): if n == 1: for d in range(1, 10): yield power_table[d] else: for s in walker4(n-1, power_table): for d in range(10): yield s + power_table[d] def nar(n): walker=walker4(n, [d**n for d in range(10)]) return [i+10**(n-1) for i,j in enumerate(walker) if i+10**(n-1)==j]
print nar(6)
[解决办法]
def nar(n): powLs=[i**n for i in range(0,9+1)] t=[i**n for i in range(1,9+1)] for i in range(n-1): t=[s+powLs[d] for s in t for d in range(0,9+1)] c=10**(n-1) return [i+c for i,j in enumerate(t) if i+c==j]