Python习题笔记

Python习题笔记


文章目录


一、六次作业代码综合

作业一

1. 输入两个整数,并打印出它们的和

代码如下(示例):

a = input('请输入第一个整数: ')
b = input('请输入第二个整数: ')

# 分别把 a、b 转换成整数
a = int(a)
b = int(b)
# 计算 a、b 的和,赋值给变量c
sum=a+b
c=sum
# 打印c
print(c)

2. 输入两个整数,如果两个整数之和小于100,则输出 ‘小于100’,否则输出 ‘不小于100’

代码如下(示例):

a = input('请输入第一个整数: ')
b = input('请输入第二个整数: ')

# 分别把 a、b 转换成整数
a = int(a)
b = int(b)
# 计算 a、b 的和,赋值给变量c
sum=a+b
c=sum
# 判断c是否小于100,按要求输出
if c < 100:
    print('小于100')
else :
    print('不小于100')    

3. 输入两组姓名和年龄,然后存入一个字典,并输出

代码如下(示例):

name1 = input('请输入第一个姓名: ')
age1= input('请输入第一个年龄: ')
name2 = input('请输入第二个姓名: ')
age2 = input('请输入第二个年龄: ')

# 分别把age1和age2转成整数
age1 = int(age1)
age2 = int(age2)
# 构造字典dict_name
dict_name = {name1:age1,name2:age2}

# 打印字典
print(dict_name)

4. 依次输入10组整数,然后求和,并输出

代码如下(示例):

sum_num = 0
for i in range(10):
    # 用input输入数字并转化为整数
    a = input ('请输入第%d个数字:'%(i+1))
    a = int(a)
    # sum_num 对输入的数字进行累加
    sum_num += a

print(sum_num)

作业二

1. 选取列表的第2到第5项,并打印(从0开始计数,即取出c d e f)

代码如下(示例):

words = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

# 选取第2-5项,并打印
s = words[2:6]
print (s)

参考输出:[‘c’, ‘d’, ‘e’, ‘f’]

2. 使用列表生成式的方法,根据 list1 生成 list2

list1 = [1, 2, 3, 4, 5, 6, 7, 8]
根据list1生成list2
list2 = [100, 200, 300, 400, 500, 600, 700, 800]

代码如下(示例):

list1 = [1, 2, 3, 4, 5, 6, 7, 8]

# 列表推导式生成list2
list2 = [n*100 for n in list1]

print(list2)

参考输出:[100, 200, 300, 400, 500, 600, 700, 800]

3. 把下列字符串按下划线(’_’)划分成若干个片段

代码如下(示例):

string1 = 'this_is_a_sample'

# 生成按'_'划分的字符串列表,即下列内容
['this', 'is', 'a', 'sample']
string1 = 'this_is_a_sample'

# 按'_'划分string1
string2=string1.split('_')
print (string2)

参考输出:[‘this’, ‘is’, ‘a’, ‘sample’]

作业三(大作业)

作业内容
统计英语6级试题中所有单词的词频,并返回一个如下样式的字典

{‘and’:100,‘abandon’:5}

英语6级试题的文件路径

./artical.txt

Tip: 读取文件的方法
  def get_artical(artical_path):
    with open(artical_path) as fr:
        data = fr.read()
    return data

get_artical('./artical.txt')
处理要求
  1. '\n’是换行符 需要删除
  2. 标点符号需要处理
    [’.’, ‘,’, ‘!’, ‘?’, ‘;’, ‘’’, ‘"’, ‘/’, ‘-’, ‘(’, ‘)’]
  3. 阿拉伯数字需要处理
    [‘1’,‘2’,‘3’,‘4’,‘5’,‘6’,‘7’,‘8’,‘9’,‘0’]
  4. 注意大小写 一些单词由于在句首,首字母大写了。需要把所有的单词转成小写
    ‘String’.lower()
    5.高分项
    通过自己查找资料学习正则表达式,并在代码中使用(re模块)

可参考资料:https://docs.python.org/3.7/library/re.html

作业四

1.'james,2006-11-11,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22’存储以上的数据,如何定义运动员类,补全代码(4分)

代码如下(示例):


class Athlete:  

    def __init__(self,a_name,a_dob=None,a_times=[]):  
    
		#代码1
      self.name = a_name
      self.dob = a_dob
      self.times = a_times
    def top3(self):
        #代码2
      return sorted(set([sanitize(t) for t in self.times]))[0:3]
    def sanitize(self,time_string):
        if '-' in time_string:
            splitter = '-'
        elif ':' in time_string:
            splitter = ':'
        else:
            return (time_string)
        (mins,secs) = time_string.split(splitter)
        return (mins+'.'+secs)

2.数据所在文件的路径为’work/james_new.txt’,使用运动员对象,补全代码(4分)

代码如下(示例):


def get_coach_data(filename): 
    with open(filename) as f: 
        line = f.readline() 
    return line.strip().split(',')

#从文件中读取数据 
#代码1
james_new = get_coach_data('work/james_new.txt')
james_name = james_new.pop(0) 
james_dob = james_new.pop(0)
#代码2
james_times = james_new
#创建Athlete对象 
#代码3
james = Athlete(james_name,james_dob,james_times)
#代码4 
print('姓名:%s,生日:%s,最快的3次成绩:%s' %(james.name,james.dob,james.top3()))

参考输出:姓名:james,生日:2006-11-11,最快的3次成绩:[‘2.01’, ‘2.22’, ‘2.34’]

3.类属性,类方法,补全代码(4分)

代码如下(示例):


class Athlete:

    #运动员集训了,要买东西的同学要把地址改一下
    #代码1
    address = '中国足球协会训练基地xx街xx号'

    def __init__(self,a_name,a_dob=None,a_times=[]):
        self.name = a_name
        self.dob = a_dob
        self.times = a_times

    def top3(self):
        return sorted(set([self.sanitize(t) for t in self.times]))[0:3]
        
    def sanitize(self,time_string):
        if '-' in time_string:
            splitter = '-'
        elif ':' in time_string:
            splitter = ':'
        else:
            return (time_string)
        (mins,secs) = time_string.split(splitter)
        return (mins+'.'+secs)
    #代码2
    @classmethod
    #代码3
    def changeAddress(self):
        self.address = '玛卡巴卡的家'
Athlete.changeAddress()
print(Athlete.address)

参考输出:玛卡巴卡的家

4.将第3题中的实例变量name改为私有的属性,将sanitize改为私有方法,补全代码(4分)

代码如下(示例):


class Athlete:
    def __init__(self,a_name,a_dob=None,a_times=[]):
        #代码1
        self.__name = a_name
        self.dob = a_dob
        self.times = a_times
       
    def sayName(self):
        #代码2
        print(self.__name)
        
    def top3(self):
        #代码3
        return sorted(set([self.__sanitize(t) for t in self.times]))[0:3]
        
    #代码4
    def __sanitize(self,time_string):
        if '-' in time_string:
            splitter = '-'
        elif ':' in time_string:
            splitter = ':'
        else:
            return (time_string)
        (mins,secs) = time_string.split(splitter)
        return (mins+'.'+secs)
        

5.数据内容james,2006-11-11,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22,以分钟.秒的形式打印’2-34’后面的所有时间。输出的结果为’2.34’, ‘3.21’, ‘2.34’, ‘2.45’, ‘3.01’, ‘2.01’, ‘2.01’, ‘3.10’, ‘2.22’,补全代码。(4分)

代码如下(示例):


data = 'james,2006-11-11,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22'

def sanitize(time_string):
	#代码1
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return (time_string)
    (mins,secs) = time_string.split(splitter)
    return (mins+'.'+secs)
#代码2
james = get_coach_data('work/james_new.txt')
name = james.pop(0)
dob = james.pop(0)
#代码3
times=[]
for each_t in james:
    times.append(sanitize(each_t))
print(times)

参考输出:[‘2.34’, ‘3.21’, ‘2.34’, ‘2.45’, ‘3.01’, ‘2.01’, ‘2.01’, ‘3.10’, ‘2.22’]

作业五

1.定义Rugby为Athlete的子类,并增加子类自己的属性squat。(5分)


class Athlete:
    def __init__(self,a_name,a_dob=None,a_times=[]):
        self.name = a_name
        self.dob = a_dob
        self.times = a_times
    def top3(self):
        return sorted(set([self.sanitize(t) for t in self.times]))[0:3]
    def sanitize(self,time_string):
        if '-' in time_string:
            splitter = '-'
        elif ':' in time_string:
            splitter = ':'
        else:
            return (time_string)
        (mins,secs) = time_string.split(splitter)
        return (mins+'.'+secs)



#代码1,定义Rugby类继承Athlete
class Rugby(Athlete):
    def __init__(self,a_name,a_dob,a_squat,a_times):
        
        #代码2,调用父类的构造方法,传递的参数为a_dob、a_times

        Athlete.__init__(self,a_name,a_dob,a_times)        
        #代码3,将a_squat赋值给类属性squat
        self.squat = a_squat
      

2.定义OtherAthlete类为Athlete类的子类,重写top3方法(允许重复的时间) (5分)


#代码1,定义OtherAthlete类继承Athlete
class OtherAthlete(Athlete):
    def __init__(self,a_name,a_bod,a_squat,a_times):
        Athlete.__init__(self,a_name,a_bod,a_times)

        self.squat = a_squat
    def top3(self):


    #代码2,定义无参数top3函数,对self.times属性应用统一化和排序功能
        return sorted([self.sanitize(t) for t in self.times ])[0:3]
        

3.定义print_rugby函数,以多态的方式调用子类属性和方法 (5分)


def get_coach_data(filename):
    with open(filename) as f:
        line = f.readline()
    return line.strip().split(',')
loren = get_coach_data('mywork/loren.txt')
mark = get_coach_data('mywork/mark.txt')

loren = Rugby(loren.pop(0),loren.pop(0),loren.pop(0),loren)
mark = OtherAthlete(mark.pop(0),mark.pop(0),mark.pop(0),mark)


def print_rugby(athlete):
    print(athlete.name)
    #代码1,打印athlete的属性dob、squat和top3方法的返回值
    print(athlete.dob)
    print(athlete.squat)
    print(athlete.top3())
    
#代码2,调用print_rugby函数,参数为loren
print_rugby(loren)
#代码3,调用print_rugby函数,参数为mark
print_rugby(mark)

参考输出:2011-11-3
270
3.59
[‘3.11’, ‘3.23’, ‘4.10’]
mark
2010-2-4
300
[‘3.11’, ‘3.11’, ‘3.23’]

4.有两个父类,一个Father,一个Mother,定义Child类共同继承这两个父类,子类调用父类的属性和方法 (5分)


class Father(): 
    def __init__(self):
        self.color = 'black'
    def talk(self):
        print("---爸爸的表达能力---")

class Mother():
    def __init__(self):
        self.height = 170
    def smart(self):
        print("---妈妈聪明的头脑---")

#代码1,定义Child类继承Father和Mother
class Child(Father,Mother):
    def __init__(self):
        #代码2,调用Mother类的的__init__方法
        Father.__init__(self)
        Mother.__init__(self)
#代码3,创建Child类的对象child,调用无参数的构造方法
child1 = Child()

#代码4,通过child调用父类的smart方法
child1.talk()
child1.smart()

#代码5,通过child打印父类的color属性
print(child1.color)
print(child1.height)

参考输出:
—爸爸的表达能力—
—妈妈聪明的头脑—
black
170

作业六(大作业)

1.输出所有的学生信息包括姓名、生日、年龄、性别、最高的3个分数。

stu1.txt 孙同学,2020-5-21,20,‘男’,77,56,77,76,92,58,-91,84,69,-91
stu2.txt赵同学,2020-11-3,24,‘女’,65,68,72,95,-81,71,86,91,57,91
stu3.txt 王同学,2021-8-7,25,‘男’,87,78,90,-76,88,47,100,65,69,100
stu4.txt 李同学,2021-8-10,29,‘男’,92,54,85,71,-91,68,77,68,95,95

以上四个txt文档在work路径下可以找到。
定义Student类,包括name、dob、age、gender和score属性,包括top3方法用来返回学生的最大的3个成绩(可重复)、sanitize方法用来将负的分数变为正的分数,负的分数可能是输入错误。声明stu_list对象组数用于存储所有的学生对象。最后输出所有的学生信息包括姓名、生日、年龄、性别、最高的3个分数。


def get_coach_data(filename):
   with open(filename) as f:
       line = f.readline()
   return line.strip().split(",")
class Student:
   def __init__(self,a_name,a_dob,a_age,a_gender,a_score=[]):
       self.name = a_name
       self.dob = a_dob
       self.age = a_age
       self.gender = a_gender
       self.score = a_score

   def top3(self):
       return sorted([self.sanitize(t) for t in self.score])[7:10]
   
   def sanitize(self,score_string):
       score_string = abs(int(score_string))
       return score_string
      
stu1 = get_coach_data('work/stu1.txt')
stu_1 = Student(stu1.pop(0),stu1.pop(0),stu1.pop(0),stu1.pop(0),stu1)
print('姓名: %s 生日: %s 年龄: %s 性别: %s 分数:%s'%(stu_1.name,stu_1.dob,stu_1.age,stu_1.gender,stu_1.top3()))

stu2 = get_coach_data('work/stu2.txt')
stu_2 = Student(stu2.pop(0),stu2.pop(0),stu2.pop(0),stu2.pop(0),stu2)
print('姓名: %s 生日: %s 年龄: %s 性别: %s 分数:%s'%(stu_2.name,stu_2.dob,stu_2.age,stu_2.gender,stu_2.top3()))

stu3 = get_coach_data('work/stu3.txt')
stu_3 = Student(stu3.pop(0),stu3.pop(0),stu3.pop(0),stu3.pop(0),stu3)
print('姓名: %s 生日: %s 年龄: %s 性别: %s 分数:%s'%(stu_3.name,stu_3.dob,stu_3.age,stu_3.gender,stu_3.top3()))

stu4 = get_coach_data('work/stu4.txt')
stu_4 = Student(stu4.pop(0),stu4.pop(0),stu4.pop(0),stu4.pop(0),stu4)
print('姓名: %s 生日: %s 年龄: %s 性别: %s 分数:%s'%(stu_4.name,stu_4.dob,stu_4.age,stu_4.gender,stu_4.top3()))

参考输出:
姓名: 孙同学 生日: 2020-5-21 年龄: 20 性别: ‘男’ 分数:[91, 91, 92]
姓名: 赵同学 生日: 2020-11-3 年龄: 24 性别: ‘女’ 分数:[91, 91, 95]
姓名: 王同学 生日: 2021-8-7 年龄: 25 性别: ‘男’ 分数:[90, 100, 100]
姓名: 李同学 生日: 2021-8-10 年龄: 29 性别: ‘男’ 分数:[92, 95, 95]

2.输出2个特长同学的姓名、生日、年龄、性别、分数、特长分。

stu5.txt 特长同学,2020-10-5,20,‘男’,180,87,98,77,76,92,58,-76,84,69,-47
stu6.txt 特长同学,2020-10-6,20,‘女’,230,76,48,82,88,92,58,-91,84,69,-68

以上两个txt文档在work路径下可以找到。
定义Spostudent、Artstudent为Student的子类,在子类的属性里面新增了spe为特长分数。Spostudent包括的top3方法返回的是最低的3个得分(可重复),Artstudent包括top3方法返回的是最高的3个得分(可重复),最后使用多态的方式输出2个特长同学的姓名、生日、年龄、性别、分数、特长分。


stu5=get_coach_data('work/stu5.txt')
stu6=get_coach_data('work/stu6.txt')
class SportStudent(Student):
    def __init__(self,a_name,a_dob,a_age,a_gender,a_sport,a_score):
        Student.__init__(self,a_name,a_dob,a_age,a_gender,a_score)
        self.spe=a_sport
    def top3(self):
        return sorted(set([self.sanitize(s) for s in self.score]),reverse=False)[0:3]
class Artstudent(Student):
    def __init__(self,a_name,a_dob,a_age,a_gender,a_art,a_score):
        Student.__init__(self,a_name,a_dob,a_age,a_gender,a_score)
        self.spe=a_art
stu_5=SportStudent(stu5.pop(0),stu5.pop(0),stu5.pop(0),stu5.pop(0),stu5.pop(0),stu5)
stu_6=Artstudent(stu6.pop(0),stu6.pop(0),stu6.pop(0),stu6.pop(0),stu6.pop(0),stu6)
def print_spe(Student):
    print('姓名:%s 生日: %s 年龄: %s 性别: %s 分数: %s 特长分: %s'%(Student.name,Student.dob,Student.age,Student.gender,Student.top3(),Student.spe))
print_spe(stu_5)
print_spe(stu_6)

参考输出:
姓名:特长同学 生日: 2020-10-5 年龄: 20 性别: ‘男’ 分数: [56, 58, 69] 特长分: 180
姓名:特长同学 生日: 2020-10-6 年龄: 20 性别: ‘女’ 分数: [91, 91, 92] 特长分: 230

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值