【百度飞桨领航团零基础Python速成营】6次作业解析

作业一:Python编程基础

课程链接:https://aistudio.baidu/aistudio/course/introduce/7073

按要求补全下列代码

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

In [13]

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

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

# 打印c
print(c)
请输入第一个整数: 
请输入第二个整数: a = 2
b =  3
5

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

In [17]

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

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

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

In [19]

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)
请输入第一个姓名: 
请输入第一个年龄: 
请输入第二个姓名: 
请输入第二个年龄: ('小明', 5, '小红', 6)

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

In [25]

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

print(sum_num)
请输入数字
请输入数字
请输入数字
请输入数字
请输入数字
请输入数字
请输入数字
请输入数字
请输入数字
请输入数字9

作业二:Python编程基础(二)

按要求完成下列代码

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

In [3]

words = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
list=words
# 选取第2-5项,
list[2:6]
['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]

In [2]

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']

In [1]

string1 = 'this_is_a_sample'

# 按'_'划分string1
string1.split('_')
['this', 'is', 'a', 'sample']

Lesson 3 大作业

作业内容

统计英语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')

处理要求

  • (a) '\n'是换行符 需要删除
  • (b) 标点符号需要处理
['.', ',', '!', '?', ';', '\'', '\"', '/', '-', '(', ')']
  • (c) 阿拉伯数字需要处理
['1','2','3','4','5','6','7','8','9','0'] 
  • (d) 注意大小写 一些单词由于在句首,首字母大写了。需要把所有的单词转成小写
'String'.lower()
  • (e) 高分项

通过自己查找资料学习正则表达式,并在代码中使用(re模块)

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

import re
# 请根据处理要求下面区域完成代码的编写。
def get_artical(artical_path):
    with open(artical_path) as fr:
        data = fr.read()
    return data

# get_artical()为自定义函数,可用于读取指定位置的试题内容。
raw_artical = get_artical('./artical.txt')

#  转小写 然后 去掉换行,标点符号,数字
raw_artical = re.sub(r'[\d\n\.\-,!\?")(:;\/]+', ' ', raw_artical.lower())

# 得到所有单词
raw_artical_list = re.split(r'\s+', raw_artical.strip())

# # 获取所有单词word数量
words = {}
for word in set(raw_artical_list):
    words[word] = raw_artical_list.count(word)

print(words)

# get_artical()为自定义函数,可用于读取指定位置的试题内容。
#get_artical('./artical.txt')
{'should': 6, 'throughout': 2, 'balance': 1, 'state': 1, 'asked': 2, 'include': 1, 'adults': 1, 'this': 9, 'proposed': 3, 'extend': 1, 'changes': 3, 'coordinator': 1, 'rising': 2, 'mutual': 1, 'retreating': 1, 'survive': 1, 'immediate': 4, 'exotic': 1, 'also': 2, 'upward': 1, 'hard': 1, 'actions': 1, 'scientific': 2, 'daunting': 1, 'power': 1, 'strongly': 1, 'holiday': 1, 'assume': 1, 'refined': 1, 'discussions': 2, 'beach': 1, 'single': 1, 'serve': 2, 'expect': 1, 'wiped': 1, "penguins'": 1, 'objects': 1, 'someone': 1, 'comes': 1, 'halting': 1, 'society': 4, 'intellectual': 1, 'once': 1, 'yet': 1, 'life': 3, 'destroy': 1, 'way': 6, 'think': 5, 'early': 1, 'tracts': 1, 'guilt': 1, 'lodging': 1, 'prepared': 1, 'organisation': 1, 'admire': 1, 'prepare': 1, 'right': 1, 'tract': 1, 'out': 7, 'highlights': 1, 'when': 7, 'neighbours': 2, "one's": 4, 'fire': 1, 'hope': 1, 'powerful': 2, 'show': 1, 'aid': 1, 'impact': 5, 'go': 1, 'aspirations': 1, 'poor': 1, 'treks': 1, "idols'": 1, 'part': 2, 'extinct': 1, 'immense': 1, 'arrive': 1, 'relations': 1, 'science': 2, 'answered': 1, 'resolving': 1, 'different': 2, 'kinds': 1, 'c': 20, "world's": 2, 'tools': 1, 'further': 3, 'action': 1, 'propagation': 1, 'opting': 1, 'mix': 1, 'however': 2, 'board': 1, 'luge': 1, 'while': 1, 'potentially': 2, 'run': 1, 'industrial': 3, 'largest': 2, 'ensuring': 1, 'repeated': 1, 'prefer': 1, 'type': 1, 'same': 2, 'ccamlr': 5, 'pupils': 4, 'report': 5, 'adventure': 1, 'that': 24, 'empty': 1, 'non': 1, 'too': 2, 'campus': 1, 'idea': 2, 'learned': 1, 'line': 3, 'define': 1, 'advice': 1, 'from': 12, 'fundraising': 2, 'devastating': 1, 'did': 2, 'determination': 1, 'person': 1, 'activities': 3, 'enable': 2, 'identity': 1, 'body': 3, 'huge': 3, 'term': 1, 'another': 2, 'how': 5, 'breeding': 11, 'bringing': 1, 'wildlife': 2, "students'": 1, 'responsibility': 1, 'beliefs': 2, 'long': 2, 'recommendation': 1, 'sustaining': 1, 'responsible': 1, 'raise': 1, 'beginnings': 1, 'contribute': 2, 'low': 1, 'latter': 1, 'sanctuary': 5, 'treatment': 1, 'things': 1, 'penguin': 7, 'needs': 1, 'region': 5, 'contact': 1, 'horizons': 2, 'shrinking': 1, 'outings': 1, 'handed': 1, 'south': 1, 'operations': 3, 'delicate': 1, 'force': 1, 'even': 4, 'source': 1, 'occur': 1, 'for': 22, 'chicks': 1, 'world': 4, 'away': 1, 'earlier': 1, 'taking': 1, 'exchange': 1, 'based': 5, 'awareness': 2, 'pressures': 3, 'in': 61, 'costs': 1, 'france': 1, 'aunts': 1, 'applauded': 1, 'nine': 1, 'she': 4, 'classroom': 1, 'exempt': 1, 'mentality': 1, 'majority': 1, 'uk': 1, 'warming': 4, 'what': 25, 'period': 1, 'hesitation': 1, 'educational': 2, 'talks': 1, 'spirit': 2, 'gender': 2, 'behave': 2, 'areas': 5, 'skills': 1, 'risks': 1, 'richer': 1, 'such': 4, 'arrange': 1, "people's": 1, 'operation': 1, 'a': 87, 'ecosystem': 3, 'regarding': 1, 'refraining': 1, 'banning': 1, 'ultimate': 1, 'creating': 1, 'be': 18, 'mammals': 1, 'consistent': 3, 'polar': 2, 'system': 1, 'kind': 1, 'each': 1, 'aiming': 1, 'few': 3, 'mistakes': 1, 'wellbeing': 1, 'he': 2, 'published': 1, 'often': 1, 'existing': 1, 'equipping': 1, 'charge': 1, 'either': 1, 'exploitation': 1, 'certain': 1, 'face': 3, 'year': 1, 'allow': 1, 'gas': 1, 'by': 6, 'something': 2, 'needed': 1, 'wilderness': 2, 'can': 10, 'changing': 2, 'sought': 1, 'group': 1, 'cultures': 1, 'babies': 1, 'justified': 1, 'interact': 1, 'manager': 2, "study's": 1, 'ideals': 1, 'have': 12, 'disappear': 3, 'little': 1, 'no': 5, 'privilege': 2, 'local': 1, 'percent': 2, 'hypocritical': 1, 'protected': 2, 'information': 1, 'frida': 1, 'want': 5, 'incidents': 1, 'had': 1, 'ones': 1, 'west': 1, 'spills': 1, 'getting': 1, 'broadening': 1, 'waters': 5, 'fuel': 2, 'pollution': 1, 'marine': 10, 'practising': 1, 'pristine': 3, 'as': 18, 'feeding': 2, 'habitats': 3, 'colonies': 6, 'species': 8, 'supports': 1, 'analysis': 1, 'say': 4, 'widen': 1, 'were': 2, 'latest': 1, 'towards': 2, 'including': 1, 'mother': 1, 'financial': 1, 'ongoing': 1, 'great': 4, 'expression': 1, 'tap': 1, 'likely': 2, 'occupy': 1, 'understand': 1, 'third': 1, 'children': 5, 'attitude': 6, 'community': 4, 'on': 25, 'goals': 2, 'suggested': 1, 'accelerated': 1, 'avoiding': 1, 'influences': 1, 'thinking': 1, 'among': 1, 'water': 3, 'starting': 1, 'its': 5, 'isolated': 2, 'possibilities': 1, 'willpower': 1, 'new': 10, 'concern': 3, 'field': 3, 'indicators': 2, "author's": 1, 'beyond': 1, 'mediate': 1, 'player': 1, 'merely': 1, 'physical': 1, 'miss': 1, 'afford': 2, 'interpersonal': 1, 'manage': 1, 'language': 1, 'initiatives': 1, 'french': 1, 'predict': 1, 'without': 2, 'found': 4, 'celine': 1, 'achieve': 1, 'condition': 1, 'pounds': 3, 'pairs': 1, 'season': 2, 'those': 6, 'all': 6, 'thriving': 1, 'circumstances': 1, 'passions': 1, 'showing': 1, 'abroad': 1, 'called': 1, 'suitable': 2, 'far': 1, 'might': 1, 'involving': 1, 'broaden': 1, 'prows': 1, "greenpeace's": 3, 'rare': 1, 'settled': 1, 'under': 1, 'syllabus': 1, 'our': 9, 'than': 3, 'are': 25, 'level': 3, 'plight': 1, 'going': 2, 'divisions': 1, 'fish': 1, 'tuesday': 1, 'bomeo': 1, 'fool': 1, 'behavior': 6, "can't": 3, 'child': 3, 'birth': 1, 'le': 3, 'cover': 3, 'find': 8, 'higher': 2, 'greenhouse': 1, 'wildernesses': 1, 'pooled': 1, 'means': 1, 'privileged': 1, 'similar': 1, 'association': 1, 'so': 1, 'peninsula': 2, 'halt': 1, 'industry': 2, "antarctic's": 1, 'becoming': 1, 'positively': 1, 'impacts': 1, 'heart': 1, 'thoughts': 2, 'case': 2, 'added': 1, 'hold': 1, 'organisations': 1, 'manages': 1, 'every': 1, 'century': 1, 'policy': 2, 'reduce': 1, 'communities': 1, 'aim': 1, 'unprecedented': 1, 'interaction': 1, 'campaign': 5, 'cannot': 3, 'endure': 1, 'her': 5, 'adjusting': 1, 'barbados': 1, 'resources': 1, 'poverty': 2, 'rise': 2, 'chance': 3, 'divided': 2, 'decision': 1, 'australia': 1, 'left': 1, 'specific': 1, 'around': 9, 'invade': 1, 'regulate': 1, 'abilities': 1, 'international': 1, 'people': 4, 'react': 1, 'startlingly': 1, 'controlling': 1, 'ambitious': 2, 'fall': 1, 'benefits': 1, 'calling': 1, 'events': 3, 'consider': 2, 'stating': 1, 'encourage': 1, 'vulnerability': 1, 'well': 2, 'drop': 1, 'friendships': 1, 'recent': 1, 'expectation': 1, 'commercial': 1, 'relationships': 1, "that's": 1, 'environmental': 1, 'celebration': 1, 'refines': 1, 'environment': 4, 'benefit': 2, 'ban': 1, 'companies': 1, 'population': 2, 'levels': 2, 'relatives': 1, 'only': 7, 'fishing': 20, "weren't": 1, 'created': 1, 'establishment': 1, 'shapes': 1, 'bengtsson': 1, 'tour': 1, 'into': 3, 'average': 1, 'loss': 1, 'doors': 1, 'will': 12, 'verge': 1, 'authority': 1, 'opposite': 1, "'s": 3, 'caring': 1, 'southern': 6, 'understanding': 2, 'big': 1, 'front': 2, 'recycling': 1, 'distance': 1, 'embodies': 1, 'lifetime': 1, 'adulthood': 1, 'better': 4, 'after': 1, 'discrepancies': 1, 'time': 5, 'operating': 1, 'continue': 1, 'must': 1, 'other': 3, 'breakfast': 1, 'said': 6, 'come': 2, 'about': 13, 'million': 1, 'feed': 2, 'clash': 1, 'accidents': 1, 'questions': 4, 'meanwhile': 1, 'truly': 1, 'primarily': 1, 'matter': 1, 'end': 1, 'your': 8, 'more': 3, 'longer': 2, 'sustain': 1, 'antarctic': 32, 'outside': 2, 'good': 3, 'later': 2, 'brink': 1, 'current': 2, 'become': 4, 'entire': 2, 'important': 2, 'place': 1, 'rich': 2, 'author': 4, 'conservation': 6, 'change': 11, 'remarkable': 1, 'do': 11, 'one': 8, 'threat': 2, 'social': 1, 'forever': 1, 'family': 2, 'groundings': 1, 'childhood': 1, 'seek': 1, 'views': 1, 'data': 2, 'baby': 1, 'ways': 3, 'publicise': 1, 'whole': 1, 'sanctuaries': 3, 'increasingly': 3, 'task': 1, 'depends': 1, 'ecosystems': 4, 'area': 4, 'courage': 1, 'off': 1, 'best': 2, 'foster': 1, 'antarctica': 4, 'abundance': 1, 'considering': 1, 'create': 1, 'acquire': 1, 'reid': 1, 'internally': 2, 'their': 28, 'adventures': 1, 'weeks': 1, 'reflect': 1, 'them': 11, 'reducing': 1, 'happen': 1, 'refinement': 1, 'whales': 7, 'seem': 1, 'scores': 1, 'proceeds': 1, 'exclude': 1, 'any': 3, 'most': 4, 'happens': 2, 'unequal': 2, 'establish': 1, 'globalised': 1, 'extinction': 2, 'experience': 2, 'caused': 1, 'both': 2, 'attractive': 1, 'kill': 2, 'initiator': 1, 'public': 1, 'guidance': 1, "daughter's": 1, 'second': 2, 'has': 5, 'attitudes': 8, 'but': 9, 'use': 1, 'vast': 1, 'despite': 1, 'these': 4, 'general': 1, 'government': 1, 'keith': 1, 'believe': 4, 'improve': 1, 'there': 5, 'especially': 1, 'passage': 11, 'effort': 1, 'sheltering': 1, 'routine': 1, 'shown': 1, 'keep': 2, 'islands': 4, 'turn': 3, 'adolescence': 1, 'global': 7, 'improvements': 1, 'climate': 7, 'kids': 2, 'like': 2, 'commission': 1, 'protecting': 1, 'populations': 1, 'receive': 1, 'pools': 1, 'feel': 4, 'behaving': 3, 'bio': 1, 'just': 3, 'requirement': 1, 'easily': 1, 'families': 2, 'disadvantaged': 4, 'b': 20, 'status': 1, 'pushed': 2, 'boost': 1, 'leading': 1, 'feeling': 1, 'involved': 1, 'age': 1, 'us': 2, 'leaving': 1, 'growing': 2, "there're": 1, 'instead': 1, 'until': 1, 'according': 5, 'trip': 3, 'scarce': 1, 'giving': 1, 'give': 1, 'handful': 1, 'expertise': 1, 'call': 1, 'distances': 1, 'wants': 1, 'large': 1, 'unspoilt': 1, 'proposal': 1, 'starkest': 1, 'boats': 1, 'below': 1, 'interference': 1, 'alleviate': 1, 'appear': 1, 'numerous': 1, 'discuss': 1, 'feelings': 2, 'key': 4, "person's": 2, 'being': 6, 'protect': 4, 'chain': 1, 'leave': 1, 'stays': 1, 'healthy': 1, 'carried': 1, 'preferential': 1, 'born': 2, 'sports': 1, 'it': 18, 'amid': 2, 'why': 3, 'considered': 1, 'sea': 7, 'access': 1, 'retreat': 1, 'gradually': 1, 'future': 4, 'following': 4, 'reserve': 1, 'because': 3, 'grounds': 10, 'parents': 5, 'disastrous': 1, 'close': 2, 'education': 1, 'bright': 1, 'takes': 1, 'which': 5, 'the': 169, 'consideration': 1, 'trips': 7, 'endangered': 1, 'could': 6, 'psychological': 3, 'expected': 2, 'purpose': 1, 'thousands': 1, 'schools': 9, 'to': 95, 'able': 2, 'damaging': 1, 'king': 15, 'then': 1, 'attention': 1, 'know': 1, 'fatal': 1, 'already': 2, 'lack': 1, 'students': 14, 'together': 2, 'filter': 1, 'worsened': 1, 'mounting': 1, 'protection': 2, 'ross': 1, 'd': 20, 'intend': 1, 'threatening': 2, 'aimed': 1, 'closer': 1, 'party': 1, 'seabirds': 1, 'been': 4, 'ideas': 1, 'transforms': 1, 'introducing': 1, 'living': 1, 'directly': 1, 'ocean': 10, 'rather': 2, 'services': 1, 'combination': 1, 'microcosm': 1, 'with': 19, 'many': 10, 'respond': 1, "don't": 7, "you'd": 1, 'improves': 1, 'probing': 1, "children's": 1, 'least': 1, 'behind': 1, 'common': 1, 'network': 1, 'income': 2, 'gap': 1, 'challenge': 1, 'birds': 1, 'migrate': 3, 'some': 6, 'personally': 1, 'culture': 1, 'over': 3, 'decide': 2, 'although': 3, 'effective': 1, 'krill': 14, 'open': 2, 'breed': 1, 'weddell': 2, 'dialogue': 2, 'who': 3, 'ideologies': 2, 'outright': 1, 'see': 4, 'ingenuity': 3, 'start': 2, 'study': 6, 'greenpeace': 3, "it's": 1, 'external': 1, 'whale': 1, 'backing': 1, 'sustainable': 2, 'tests': 1, 'receiving': 1, 'does': 8, 'soon': 1, 'or': 9, 'provider': 1, 'interpret': 1, 'volunteering': 1, 'help': 6, 'ice': 2, 'launched': 3, 'example': 2, 'exercise': 1, 'develop': 1, 'we': 13, 'anything': 1, 'not': 10, 'burden': 1, 'school': 6, 'studies': 2, 'separate': 2, 'seals': 1, 'they': 30, 'eyes': 1, 'month': 1, 'if': 6, 'discrepancy': 1, 'apparent': 1, 'knowledge': 1, 'oil': 1, "today's": 1, 'governmental': 1, 'conference': 1, 'opportunities': 3, 'motivate': 1, 'particularly': 1, 'posed': 2, 'strasbourg': 1, 'co': 1, 'temperatures': 2, 'always': 1, 'between': 3, 'up': 2, 'university': 1, 'operate': 1, 'though': 3, 'glamorous': 1, 'hospital': 1, 'backgrounds': 1, 'melting': 1, 'predicts': 1, 'movements': 1, 'warms': 1, 'rock': 1, 'suggest': 2, 'serious': 1, 'complex': 1, 'happened': 1, 'vessels': 1, 'bring': 1, 'easy': 2, 'role': 1, 'build': 1, 'now': 1, 'determines': 1, 'particular': 1, 'states': 1, 'two': 3, 'where': 1, 'vicinity': 1, 'unless': 1, 'voluntarily': 1, 'penguins': 17, 'handle': 1, 'burdens': 1, 'behaviors': 1, 'methods': 1, 'creation': 1, 'three': 1, 'ignore': 1, 'achievements': 1, 'strategy': 1, 'october': 1, 'an': 9, 'emissions': 1, 'at': 7, 'live': 1, 'food': 4, 'is': 34, 'pull': 1, 'depriving': 1, 'travel': 3, 'relocate': 2, 'movement': 1, 'participate': 2, 'you': 15, 'distinctive': 1, 'much': 2, 'dying': 1, 'act': 1, 'predicting': 1, 'findings': 2, 'cost': 2, 'warned': 1, 'learn': 4, 'was': 10, 'analysed': 1, 'whom': 1, 'department': 1, 'during': 2, 'and': 74, 'nearer': 1, 'necessarily': 1, 'pace': 1, 'number': 1, 'forced': 2, 'seas': 4, 'years': 1, 'last': 3, 'expensive': 1, 'sense': 1, 'sensitive': 1, 'profit': 1, 'identify': 1, 'almost': 1, 'get': 1, 'happening': 1, 'reluctant': 1, 'hungry': 2, 'interviewed': 1, 'induced': 1, 'require': 2, 'sub': 1, 'says': 2, 'gaps': 1, 'of': 82, 'overfishing': 2, 'presence': 1, 'may': 10, 'human': 3, 'nutrient': 1, 'take': 2, 'would': 3, 'rarely': 1, 'concerned': 1, 'bohec': 3}

第1题

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

存储以上的数据,如何定义运动员类,补全代码(4分)

In [ ]

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)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
a = Athlete('james,2006-11-11,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22')
print(a.name,a.dob,a.top3)
james,2006-11-11,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22 None <bound method Athlete.top3 of <__main__.Athlete object at 0x7f28626e3650>>

第2题

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

In [ ]

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) 
james_times = james_new
#创建Athlete对象 




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

#代码3
    def top3(self):
        return sorted(set([self.sanitize(t) for t in self.times]))[0:3]

#代码4 
james = Athlete('james,2006-11-11,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22')
#print('姓名:%s,生日:%s,最快的3次成绩:%s' %())
print('姓名:%s,生日:%s,最快的3次成绩:%s' %(james.name,james.dob,james.top3()))
姓名:james,2006-11-11,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22,生日:None,最快的3次成绩:[]

第3题

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

In [ ]

class Athlete:

    #运动员集训了,要买东西的同学要把地址改一下
    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)
    @classmethod
    def changeAddress(self):
        self.address = '中国足球协会训练基地xx街xx号'
        Athlete.changeAddress()
print(Athlete.address)
中国足球协会训练基地xx街xx号

第4题

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

In [23]

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 sayName(self):
           print(self._name)

     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)

第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分)

In [26]

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 = data.split(',')
name = james.pop(0)
dob = james.pop(0)
times = sanitize(james)

#代码3
print(times)
['2-34', '3:21', '2.34', '2.45', '3.01', '2:01', '2:01', '3:10', '2-22']

第1题

In [66]

#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)

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

#代码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题

In [67]

#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_squat,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题

In [68]

#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)
    print(athlete.dob)
    print(athlete.squat)
    print(athlete.top3())
    
#代码2,调用print_rugby函数,参数为loren
print_rugby(loren)
#代码3,调用print_rugby函数,参数为mark
print_rugby(mark)
loren
2011-11-3
270
['3.11', '3.23', '3.59']
mark
300
300
['3.11', '3.11', '3.23']

第4题

In [69]

#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.smart()

#代码5,通过child打印父类的color属性
print(child1.color)
---妈妈聪明的头脑---
black

第一题(30分)

数据如下:

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个分数。

第一题的输出结果如下,供参考:

In [4]

class Student():
    def __init__(self,name,dob,age,gender,score):
        self.name = name
        self.dob = dob
        self.age = age
        self.gender = gender
        self.score = score
    def top3(self):
        c = self.sanitize(self.score)  # 去除'-'减号
        c.sort(reverse = True)  # 倒序排序
        c = [int(i) for i in c]  # 转化为整式
        if c.count(100):  # 100分为特殊情况单独考虑,如果有的话要多写一步
            return (c[-c.count(100):]+c[:-c.count(100)])[:3]  # 将一百分的成绩移到最前面
        else:
            return c[:3]
    def sanitize(self,score):
        return [i.replace('-','') for i in score]  # 去除减号'-'

 
  # 读取文件信息
list1 = []

for i in range(1,5):  # 读取第1到第4份文件
    with open('work/stu%s.txt'%i) as f:
        list1.extend(f.readlines())
list1 = [i.split(',') for i in list1]  # 将字符串转化为列表
  # 创建实例
stu_list = [Student(i[0],i[1],i[2],i[3],i[4:]) for i in list1]  # 创建的4个学生实例


for i in stu_list:
    print('姓名:',i.name,'生日:',i.dob,'年龄:',i.age,'性别:',i.gender,'分数',i.top3())  # 输出需要的学生信息

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

第二题(30分)

数据格式如下:

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个特长同学的姓名、生日、年龄、性别、分数、特长分。

第二题的输出结果如下,供参考:

In [2]

class Spostudent(Student):
    def __init__(self,name,dob,age,gender,score,spe):
        Student.__init__(self,name,dob,age,gender,score)
        self.spe = spe
    def top3(self):
        c = self.sanitize(self.score)    # 去除减号'-'
        c.sort()  # 正序排序
        c = [int(i) for i in c]
        if c.count(100):  # 100分为特殊情况单独考虑,有100分的话要多写一步
            return (c[c.count(100):]+c[:c.count(100)])[:3]  # 将100分的成绩移到最后面
        else:
            return c[:3]

  # 与父类只多了1个“艺术分”,就多1行代码就行
class Artstudent(Student):
    def __init__(self,name,dob,age,gender,score,spe):
        Student.__init__(self,name,dob,age,gender,score)
        self.spe = spe

  # 读取第5份、第6份文件
list1 = []
for i in range(5,7):
    with open('work/stu%s.txt'%i) as f:
        list1.extend(f.readlines())
list1 = [i.split(',') for i in list1]
  # 创建实例
stu_list = []
for n,i in enumerate(list1):
    if n==0:
        stu_list.extend([Spostudent(i[0],i[1],i[2],i[3],i[5:],i[4])])
    else:
        stu_list.extend([Artstudent(i[0],i[1],i[2],i[3],i[5:],i[4])])

for i in stu_list:
    print('姓名:',i.name,'生日:',i.dob,'年龄:',i.age,'性别:',i.gender,'分数',i.top3(),'特长分',i.spe)

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

更多推荐

2021-02-17