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


    #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
    
  • 相关阅读:
    利用border-radius画椭圆
    关于使用svg构建六边形蜂巢列表的方式
    JavaScript拖拽效果的原理及实现
    逆战班-JS的形参与实参
    前端面试&笔试汇总
    less学习---less的混合(mixin)
    less学习---less的嵌套规则
    less学习----less变量
    vue-cli3实现将数据导出为Excel表
    js中apply和call方法浅析
  • 原文地址:https://www.cnblogs.com/tuzkee/p/2908603.html
Copyright © 2020-2023  润新知