【每日一题0704】反向阶乘

霍格沃茨的魔法师们一定很熟悉阶乘,也就是整数的乘积。例如,5! = 120,因为5 * 4 * 3 * 2 * 1 = 120

今天邓布利多教授交给我们的挑战是创建一个接受任意数字,并返回其阶乘的数字的函数。例如接收到120,它应返回数字5

当然,不是每个数都是另一个数的阶乘。在这种情况下,请返回None

题目难度:中等
题目来源:codewars

def reverse_fac(num):
    pass

assert reverse_fac(120) == 5
assert reverse_fac(24) == 4
assert reverse_fac(150) is None
def reverse_fac(num):
    results=1
    n_fact=None
    for i in range(1,num+1):
        results*=i
        if results==num:
            n_fact=i
            break
    return n_fact
def reverse_fac(num):
    """反向阶乘"""
    fac = 1
    n = None
    for i in range(1, int(num/2)):
        fac *= i
        if fac == num:
            n = i
            break
    return n

def reverse_fac(num):
    n = 1
    sum_number = 1
    while sum_number < num:
        n += 1
        sum_number *= n
    if sum_number!=num:
        return None
    else:
        return n


assert reverse_fac(120) == 5
assert reverse_fac(24) == 4
assert reverse_fac(150) is None

如果是2呢

题解1:常规思路

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

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

结果是对的

def fn(x):
    for i in range(1,x+1):
        if x%i==0:
            x=x/i
            if x==1:
                return i
        else:
            return None

print(fn(120),fn(24),fn(150))