zoukankan      html  css  js  c++  java
  • [深入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
    
  • 相关阅读:
    条件概率融合
    径向函数,随机映射,SVM, 或者特征提取都是一类策略
    神经网络结构搜索
    NetCDF
    你应该看到更多
    Focal Loss for Dense Object Detection
    胶囊网络
    seq2seq模型
    编译lua解析器和lua动态库
    JavaScript Json数组的简单使用
  • 原文地址:https://www.cnblogs.com/tuzkee/p/2908603.html
Copyright © 2011-2022 走看看