def reverse_fac(num):
for i in range(1,num):
if num % i != 0:
return None
if num/i == 1:
return i
num /= i
assert reverse_fac(120) == 5
assert reverse_fac(24) == 4
assert reverse_fac(150) is None
题解2: 归约函数(纯属娱乐)
from functools import reduce
def reverse_fac(num):
for i in range(1, num):
result = reduce(lambda x,y:x/y, [num] + list(range(1, i+1)))
if result == 1.0:
return i
if result < 1:
return None
assert reverse_fac(120) == 5
assert reverse_fac(24) == 4
assert reverse_fac(150) is None
题解3:生成器(纯属娱乐)
import itertools
import operator
def reverse_fac(num):
for i in range(1, num):
result = list(itertools.accumulate([num] + list(range(1, i+1)), operator.truediv))[-1]
if result == 1.0:
return i
if result < 1:
return None
assert reverse_fac(120) == 5
assert reverse_fac(24) == 4
assert reverse_fac(150) is None