Python 练习题及其总结

1.计算今年是闰年嘛?判断闰年条件, 满足年份模400为0, 或者模4为0但模100不为0.

  ### 使用了import, time模块, 逻辑分支, 字串格式化等

#coding:utf-8
'''cdays-5-exercise-1.py 判断今年是否是闰年
    @note: 使用了import, time模块, 逻辑分支, 字串格式化等
'''

import time                             #导入time模块
thisyear = time.localtime()[0]             #获取当前年份
if thisyear % 400 == 0 or thisyear % 4 ==0 and thisyear % 100 <> 0: #判断闰年条件, 满足模400为0, 或者模4为0但模100不为0
    print 'this year %s is a leap year' % thisyear
else:
    print 'this year %s is not a leap year' % thisyear
Conclusion:Conclusion:
  1.相同执行顺序的代码左边对齐,否则会出错。
  2.字符串中引用参数,注意print里的语句 :  '  ***** %s **** '   % thisyear


2.利用python作为科学计算器。熟悉Python中的常用运算符,并分别求出表达式12*34+78-132/6、(12*(34+78)-132)/6、(86/40)**5的值。并利用math模块进行数学计算,分别求出145/23的余数,0.

   ###基本表达式运算, 格式化输出, math模块

#coding:utf-8
'''cdays-5-exercise-2.py 求表达式的值
    @note: 基本表达式运算, 格式化输出, math模块
    @see: math模块使用可参考http://docs.python.org/lib/module-math.html
'''

x = 12*34+78-132/6      #表达式计算
y = (12*(34+78)-132)/6
z = (86/40)**5

print '12*34+78-132/6 = %d' % x
print '(12*(34+78)-132)/6 = %d' % y
print '(86/40)**5 = %f' % z

import math             #导入数学计算模块

a = math.fmod(145, 23)  #求余函式
b = math.sin(0.5)       #正弦函式
c = math.cos(0.5)       #余弦函式

print '145/23的余数 = %d' % a
print 'sin(0.5) = %f' %b
print 'cos(0.5) = %f' %c
Conclusion:

1.整数除法运算:  // 是整除,但是 /  在整数运算中竟然也是整除。如果要小数可以添加小数点。

2.math模块函数以后还要多找一些,math.fmod(a,b)求余

3.找出0~100之间的所有素数。

###for 循环,列表循环

#coding:utf-8
'''cdays-5-exercise-3.py 求0~100之间的所有素数
    @note: for循环, 列表类型
    @see: math模块使用可参考http://docs.python.org/lib/module-math.html
'''

from math import sqrt

N = 100
#基本的方法
result1 = []
for num in range(2, N):
    f = True
    for snu in range(2, int(sqrt(num))+1):
        if num % snu == 0:
           f = False
           break
    if f:
        result1.append(num)
print result1

#更好的方法
result2 = [ p for p in range(2, N) if 0 not in [ p% d for d in range(2, int(sqrt(p))+1)] ]
print result2
Conclusion:

1. import  dir1.dir2.mod        导入  \dir1\dir2\mod模块 ,这里的点代表目录,dir1目录下的dir2目录,然后dir2目录里的mod模块

2.from dir1.dir2.mod import x        a)导入mod里的子模块 x  

                                                             b)避免重复输入路径,这样之后的模块导入直接 import mod.x  ,如果之前没有,则必须import dir1.dir2.mod.x

3.列表添加元素,result.append( x )


4.读取文件cdays-4-test.txt内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为cdays-4-result.txt。

  • cdays-4-test.txt

    #some words
    
    Sometimes in life,
    You find a special friend;
    Someone who changes your life just by being part of it.
    Someone who makes you laugh until you can't stop;
    Someone who makes you believe that there really is good in the world.
    Someone who convinces you that there really is an unlocked door just waiting for you to open it.
    This is Forever Friendship.
    when you're down,
    and the world seems dark and empty,
    Your forever friend lifts you up in spirits and makes that dark and empty world
    suddenly seem bright and full.
    Your forever friend gets you through the hard times,the sad times,and the confused times.
    If you turn and walk away,
    Your forever friend follows,
    If you lose you way,
    Your forever friend guides you and cheers you on.
    Your forever friend holds your hand and tells you that everything is going to be okay. 

    #coding:utf-8
    '''cdays-4-exercise-6.py 文件基本操作
        @note: 文件读取写入, 列表排序, 字符串操作
        @see: 字符串各方法可参考hekp(str)或Python在线文档http://docs.python.org/lib/string-methods.html
    '''
    
    f = open('cdays-4-test.txt', 'r')                   #以读方式打开文件
    result = list()
    for line in f.readlines():                          #依次读取每行
        line = line.strip()                             #去掉每行头尾空白
        if not len(line) or line.startswith('#'):       #判断是否是空行或注释行
            continue                                    #是的话,跳过不处理
        result.append(line)                             #保存
    result.sort()                                       #排序结果
    print result
    open('cdays-4-result.txt', 'w').write('%s' % '\n'.join(result)) #保存入结果文件
    
    Conclusion:

             1.f = open( ' FileName', 'w')    括号内r, w, 等等都可以

             2.for line in f.readlines()             f.readlines()整行读取

             3.line.startswith('#')    line以 # 开头


5.读取某一简单索引文件cdays-3-test.txt,其每行格式为文档序号 关键词,现需根据这些信息转化为倒排索引,即统计关键词在哪些文档中,格式如下:包含该关键词的文档数 关键词 => 文档序号。其中,原索引文件作为命令行参数传入主程序,并设计一个collect函式统计 "关键字<->序号" 结果对,最后在主程序中输出结果至屏幕。

  • cdays-3-test.txt 内容:

    1 key1
    2 key2
    3 key1
    7 key3
    8 key2
    10 key1
    14 key2
    19 key4
    20 key1
    30 key3

  •  '''cdays-3-exercise-2.py 字典的使用
        @not: 使用sys.args, 字典操作, 函式调用
        @see: sys模块参见help(sys)
    '''
    
    import sys                                          #导入sys模块
    
    def collect(file):
        ''' 改变 key-value对为value-key对
        @param file: 文件对象
        @return: 一个dict包含value-key对
        '''
        result = {}
        for line in file.readlines():                   #依次读取每行
            left, right = line.split()                  #将一行以空格分割为左右两部分
            if result.has_key(right):                   #判断是否已经含有right值对应的key
                result[right].append(left)              #若有,直接添加到result[right]的值列表
            else:
                result[right] = [left]                  #没有,则新建result[right]的值列表
        return result
    
    if __name__ == "__main__":
        if len(sys.argv) == 1:                          #判断参数个数
            print 'usage:\n\tpython cdays-3-exercise-2.py cdays-3-test.txt'
        else:
            result = collect(open(sys.argv[1], 'r'))    #调用collect函式,返回结果
            for (right, lefts) in result.items():       #输出结果
                print "%d '%s'\t=>\t%s" % (len(lefts), right, lefts)
    


     Conclusion:

               1.string 按空格分割    left, right = line.split()

               2.字典按照key 查找    if  result.has_key(right):

               3.结构:result[right].append(left)

               4.参数    if __name__ == "__main__":

                                         result = collect( sys.argv[1],'r')

              5.按照元素读取字典:

                                         for(right,left) in result.items():

                                               print right,left


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值