|
60鱼币
1. 请编写一个类 Int,该类有一个成员属性 num,一个成员方法 getSum(),该方法计算属性 num 各个数位上的数字之和,返回指定输出格式的字符串对象,如输入“123”,输出为:“123 的各个数位上的数字之和为 6”,还有一个构造方法__init__(),用来传入一个 3 位正整数,初始化成员属性 num。请编写代码实现类 Int 并进行调用。
2. 如下代码生成一组学生的 Python 课程成绩,请编写函数 get_scores_info(scores),完成对 scores 列表中[0,60)、[60, 80)、[80, 90)、[90, 100]区间成绩的占比(百分比)的统计,并按照指定格式输出,输出格式形如:[0,60)占比为 15%。 import random scores = [random.randint(0,100) for i in range(200)]
3. 有如下内容:
#name,age,score tom,12,86
Lee,15,99
Lucy,11,58
Joseph,19,56
请编写代码完成以下功能:
1)将上述内容写入文件 e:\record.txt;
2)将文件中 score 低于 60 分记录的 name 输出;
3)计算文件中所有记录的 score 之和并输出。
- # 1
- class Int:
- def __init__(self, num):
- self.num = num
-
- def getSum(self):
- s = sum(map(int, self.num))
- prompt = f"{self.num}的各个数位上的数字之和为{s}"
- return prompt
- if __name__ == "__main__":
- i = Int("123")
- print(i.getSum())
- # 2
- import random
- scores = [random.randint(0,100) for i in range(200)]
- def get_scores_info(scores):
- p0_60 = len([i for i in scores if i in range(0, 60)]) / len(scores)
- p60_80 = len([i for i in scores if i in range(60, 80)]) / len(scores)
- p80_90 = len([i for i in scores if i in range(80, 90)]) / len(scores)
- p90_100 = len([i for i in scores if i in range(90, 101)]) / len(scores)
-
- kinds = ("[0, 60)", "[60, 80)", "[80, 90)", "[90, 100]")
- nums = (p0_60, p60_80, p80_90, p90_100)
- s_dict = dict(zip(kinds, nums))
- for i in kinds:
- print(f"{i}占比为{s_dict[i] * 100}%")
- if __name__ == "__main__":
- get_scores_info(scores)
- # 3
- text = """name,age,score
- tom,12,86
- Lee,15,99
- Lucy,11,58
- Joseph,19,56"""
- with open(r"e:\record.txt", "w", encoding="utf-8") as f:
- f.write(text)
- with open(r"e:\record.txt", "r", encoding="utf-8") as f:
- data = f.read().splitlines()[1:]
- sum_score = 0
- for l in data:
- r = l.split(",")
- s = float(r[-1])
- sum_score += s
- if s < 60:
- print(r[0])
- print(sum_score)
复制代码
|
|