[深入Python]简单事情复杂化:Python计算阶乘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#coding:utf-8
 
def new(cls, *args, **kwargs):
    '''
    若cls是函数,则调用之;若cls是类型,则生成一个cls类型的对象
    '''
    return cls(*args, **kwargs)
 
class Number(object):
    pass
 
class IntegralNumber(int, Number):
    '''
    整数类,自定义了一个toInt函数,可以把自己转换为一个int型。
    折腾了半天,x=IntegralNumber(3) 最终就是x=3
    '''
    def toInt(self):
        return new (int, self)
 
class InternalBase(object):
    '''
    按设计者的意思,每个数学系统(StandardMathematicsSystem)应该有个基数
    该类就是来表示这个基数的,这里的StandardMathematicsSystem的基数是2
    '''
    def __init__(self, base):
        self.base = base.toInt()
 
    def getBase(self):
        return new (IntegralNumber, self.base)
 
class MathematicsSystem(object):
    '''
    MathematicsSystem实现了一个最简单的单例类,需通过getInstance获取实例
    '''
    def __init__(self, ibase):
        Abstract
 
    @classmethod
    def getInstance(cls, ibase):
        try:
            cls.__instance
        except AttributeError:
            cls.__instance = new (cls, ibase)
        return cls.__instance
 
class StandardMathematicsSystem(MathematicsSystem):
    '''
    用于计算的数学系统
    '''
    def __init__(self, ibase):
        '''
        验明基数
        '''
        if ibase.getBase() != new (IntegralNumber, 2):
            raise NotImplementedError
        self.base = ibase.getBase()
 
    def calculateFactorial(self, target):
        '''
        实际干活
        '''
        result = new (IntegralNumber, 1)
        i = new (IntegralNumber, 2)
        while i <= target:
            result = result * i
            i = i + new (IntegralNumber, 1)
        return result
 
 
print StandardMathematicsSystem.getInstance(new (InternalBase, new (IntegralNumber, 2))).calculateFactorial(new (IntegralNumber, 6)) #720

 

posted @   鸪斑兔  阅读(1864)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示