zoukankan      html  css  js  c++  java
  • python小练习之一

    下面的练习本身不难,比如打印1到10,计算1+2+3+...+100 ,最后一个是计算 1-2+3-4...-100
    用了类的方法实现
    用了列表生成器
    用“高级”一丢丢的写法来实现这些小练习

    # coding:utf-8
    
    class Num(object):
    
        def __init__(self, calNum):
            self.calNum = calNum
    
        @property
        def seqNum(self):
            i = 0
            while i < self.calNum:
                i += 1
                yield i
    
        @property
        def sumNum(self):
            return reduce(lambda sum, x: sum + x, xrange(self.calNum))
    
        @property
        def oddNum(self):
            return [ num for num in range(self.calNum) if num % 2 != 0 ]
    
        @property
        def evenNum(self):
            return [ num for num in range(self.calNum) if num % 2 == 0 ]
    
        @property
        def crossSumNum(self):
            sum = 0
            for i in xrange(self.calNum):
               if i % 2 == 0:
                   sum = sum - i
               else:
                   sum = sum + i
            return sum
    
    
    def Main():
        print "======================="
        print u"输出1,2,3...10"
        print "======================="
        n = Num(10)
        for i in n.seqNum:
            print i,
        print "\r"
        print "======================="
        n = Num(101)
        print u"求和1+2+3+...+100"
        print "======================="
        print n.sumNum
        print "======================="
        print u"输出1...100范围的奇数"
        print "======================="
        for i in n.oddNum:
            print i,
        print "\r"
        print "======================="
        print u"1...100范围的偶数"
        print "======================="
        for i in n.evenNum:
            print i,
        print "\r"
        print "======================="
        print u"求和1-2+3-4-5+6...+100"
        print "======================="
        print n.crossSumNum
    
    if __name__ == '__main__':
        Main()
    
  • 相关阅读:
    app分析报告试验
    NABCD模式试验
    课堂练习
    学生管理系统测试计划及测试矩阵
    图书管理系统活动,时序图
    图书借阅测试用例UML图
    风险分析
    需求规格说明说
    PM的定义跟功能说明模块
    需求分析-NABCD
  • 原文地址:https://www.cnblogs.com/haozike/p/python_exercises_1.html
Copyright © 2011-2022 走看看