|
发表于 2017-1-13 23:12:27
|
显示全部楼层
- # encoding:utf-8
- # 1! + 4! + 5! = 145 找类似组合
- from time import time
- from math import factorial
- from itertools import permutations
- def euler034():
- l_facs = [factorial(x) for x in range(0, 10)]
- print(l_facs)
- for f in range(2, 7):
- l_temp = [k for (k, v) in enumerate(l_facs) if v < 10 ** f]
- for each in permutations(l_temp, f):
- n_t = ''
- nums = 0
- for t in each:
- n_t += str(t)
- nums += l_facs[t]
- if nums == int(n_t):
- print(nums)
- def euler034_1():
- l_facs = [factorial(x) for x in range(0, 10)]
- print(l_facs)
- for i in range(11, l_facs[9] * 7):
- tmp = list(str(i))
- sums = sum([l_facs[int(k)] for k in tmp])
- if i == sums:
- print(i)
- if __name__ == '__main__':
- start = time()
- euler034()
- print('cost %.6f sec' % (time() - start))
- start = time()
- euler034_1()
- print('cost %.6f sec' % (time() - start))
复制代码
一种用排列,不含重复数字的;一种暴力求解,可以喊重复数字。结果如下:
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
145
cost 0.481362 sec
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
145
40585
cost 8.705163 sec
|
|