设为首页 收藏本站
查看: 694|回复: 0

[经验分享] python基础的几个小练习题

[复制链接]
累计签到:6 天
连续签到:1 天
发表于 2015-11-29 14:45:22 | 显示全部楼层 |阅读模式
  题目:
  1、写一个程序,判断2008年是否是闰年。
  2、写一个程序,用于计算2008年10月1日是这一年的第几天?(2008年1月1日是这一年的第一天)
  3、(文件题)有一个“record.txt”的文件,内容如下:



# name, age, score

tom, 12, 86
Lee, 15, 99
Lucy, 11, 58
Joseph, 19, 56
  第一栏为姓名(name),第二栏为年纪(age),第三栏为得分(score)
  现在,写一个Python程序,
  1)读取文件
  2)打印如下结果:
  得分低于60的人都有谁?
  谁的名字以L开头?
  所有人的总分是多少?
  3)姓名的首字母需要大写,该record.txt是否符合此要求? 如何纠正错误的地方?
  4、(练习正则表达式)有一个文件,文件名为output_1981.10.21.txt 。下面使用Python: 读取文件名中的日期时间信息,并找出这一天是周几。将文件改名为output_YYYY-MM-DD-W.txt (YYYY:四位的年,MM:两位的月份,DD:两位的日,W:一位的周几,并假设周一为一周第一天)
  以下是程序清单:



  1 #-*-coding:utf-8 -*-
  2
  3 # (1) judge leap year
  4 def judge_leap_year(n):
  5     # if n%4 == 0 and n%100 != 0:
  6     #     return True
  7     # if n%100 == 0 and n%400 == 0:
  8     if (n%4 == 0 and n%100 != 0) or (n%100 == 0 and n%400 == 0):
  9         return True
10     else:
11         return False
12
13 # ===================================================================
14 # (2) computing the sum days of any day(**.**.**)
15 def compute_year_counts(datestr):
16     # deal with these case:
17     # 2012.12.2
18     # 2012/12/2
19     # 2012-12-2
20     if datestr.find('.') > 0: date = datestr.split('.')
21     if datestr.find('/') > 0: date = datestr.split('/')
22     if datestr.find('-') > 0: date = datestr.split('-')
23
24     year = int(date[0])
25     month = int(date[1])
26     day = int(date[2])
27     if (month < 1 or month > 12):
28         print "the error month!"
29         return -1
30     if (day > 31):
31         print "the error day!"
32         return -1
33
34     days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
35
36     # nDays = 0
37     # i = 1
38     # while i < month:
39     #     nDays += days[i-1]
40     #     i = i + 1
41     nDays = sum(days for i in range(0, month - 1))
42     if (judge_leap_year(year)):
43         nDays += 1
44     return nDays + day
45
46 datestring = raw_input("input the datetime info:-->")
47 print compute_year_counts(datestring)
48
49 # ===================================================================
50 # (3) read and write file: use class if perfect!
51 class UserProfier(object):
52     def __init__(self, name, age, score):
53         self.name = name
54         self.age = age
55         self.score = score
56
57 def read_file_and_anlysis(filetext):
58     line_read = []
59     user_scores = []
60     has_invalid_name = False #the invalid name
61
62     for line in filetext:
63         if not line.startswith('#') and len(line.strip()) != 0:
64             if line[0].islower():
65                 line = line[0].upper() + line[1:]
66                 has_invalid_name = True
67             cur = line.strip().split(', ')
68             user_scores.append(UserProfier(cur[0], int(cur[1]), int(cur[2])))
69             line_read.append(line)
70     # print the file
71     print "print the file"
72     for i in line_read:
73         print i
74     # statistic the score < 60
75     print "users whose score lower 60:"
76     for scores in filter(lambda s: s.score < 60 , user_scores):
77         print scores.name
78     # statistic the begin of name which is 'L'
79     print "users whose name's begin is 'L':"
80     for names in filter(lambda s: s.name.startswith('L'), user_scores):
81         print names.name
82     # statistic the total scores of all one
83     print "the total scores of everyone:"
84     allscores = map(lambda s:s.score, user_scores)
85     print allscores
86     print reduce(lambda x, y: x+y, allscores, 0)
87
88 # open the file
89 with open("record.txt") as f:
90     read_file_and_anlysis(f)
91
92 # ===================================================================
93 # (4) the useful example of regular expression
94 import os, re, datetime
95
96 filename = "output_1981.10.21.txt"
97
98 date_time = re.search("(?P<year>\d{4})\.(?P<month>\d{2})\.(?P<day>\d{2})\.", filename)
99
100 year = date_time.group('year')
101 month = date_time.group('month')
102 day = date_time.group('day')
103
104 print year, month, day
105 date = datetime.date(int(year), int(month), int(day))
106 w = date.weekday() + 1
107 W = str(w)
108 os.rename(filename, "output_"+year+'-'+month+'-'+day+'-'+str(w)+".txt")
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-144993-1-1.html 上篇帖子: lda模型的python实现 下篇帖子: Spark SQL编程指南(Python)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表