本篇文章小编给大家分享一下python计算数字或者数组的阶乘实现代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
# -*- coding:utf-8 -*- """ author: 15025 time: 2021/7/18 17:58 software: PyCharm Description: calculate factorial of a given number """ class PythonStudy: @staticmethod def factorial(n): num = 1 for i in range(1, n + 1): num *= i return num if __name__ == "__main__": main = PythonStudy() result = main.factorial(4) print("The final result is: ") print(result) """ The final result is: 24 """
可以看到,我们正确地获得了4的阶乘值24。那么如果我们需要求一个数组中各个元素的阶乘值呢?
# -*- coding:utf-8 -*- """ author: 15025 time: 2021/7/18 17:58 software: PyCharm Description: calculate factorial of a given array """ import numpy as np class NumpyStudy: @staticmethod def factorial(arr): length = len(arr) num_arr = np.ones(length) for index, value in enumerate(arr): for i in range(1, value + 1): num_arr[index] *= i return num_arr if __name__ == "__main__": main = NumpyStudy() array = np.arange(11) result = main.factorial(array) print("The final result is: ") print(result) """ The final result is: [1.0000e+00 1.0000e+00 2.0000e+00 6.0000e+00 2.4000e+01 1.2000e+02 7.2000e+02 5.0400e+03 4.0320e+04 3.6288e+05 3.6288e+06] """
这里我们可以看到我们成功获得了数组[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]中对应的的各个元素值的阶乘值。