题目1
模拟评委给选手打分。选手最后得分为去掉一个最高分去掉一个最低分之后的平均分。
scores = []
n = int(input("请输入评委的人数:"))
for i in range(n):
score = int(input("请输入第{}个分数:".format(i+1)))
scores.append(score)
scores.remove(max(scores))
scores.remove(min(scores))
# del scores[scores.index(max(scores))] # 最大值,最小值所在索引
# del scores[scores.index(min(scores))]
print("avg_score:", sum(scores)/len(scores))
# 改变输入方式,一次性输入,空格隔开
sstring = input('please input score 1 to score n:')
scores = sstring.split()
scores = [int(i) for i in scores]
del scores[scores.index(max(scores))]
del scores[scores.index(min(scores))]
print("avg_score:", sum(scores)/len(scores))
题目2
根据系统当前时间,显示不同的问候语。具体要求如下:
0~6(不含6点):深夜还在工作,身体和你有仇吗?
6~12(不含12点):上午要努力工作哦,加油。
12~18(不含18点):下午脑子易疲劳,干点轻松的活吧。
18~24(不含24点):晚上了,身体需要好好休息,请关机。
除了if语句实现外(若用多分支语句,显得代码较长),把四个问候语按照时间顺序存储在一个元组中。因为本例时间段划分是均等的,都是以6小时为一个间隔,所以当前时间的小时数对6整除的结果就是对应的问候语在元组中的索引。
from datetime import datetime
greetings = ('深夜还在工作,身体和你有仇吗?', '上午要努力工作哦,加油。',
'下午脑子易疲劳,干点轻松的活吧。', '晚上了,身体需要好好休息,请关机。')
now_hour = datetime.now().hour
print(greetings[now_hour//6]) # 每个时间段长度是6,索引等于当前时间除以6
现时间段划分不均等,具体要求如下: 0~5(不含5点):深夜还在工作,身体和你有仇吗? 5~8(不含8点):好好利用清晨的时间。 8~11(不含11点):上午努力工作。 11~14(不含14点):中午来场午休吧。 14~18(不含18点):下午脑子易疲劳,干点轻松的活吧。 18~21(不含21点):傍晚了,听听音乐看看书吧。 21~24(不含24点):晚上了,身体需要好好休息,请关机。
使用提供二分查找的bisect模块。
根据时间界限点再构造一个有序的时间元组,
利用bisect模块中的bisect()方法查找当前时间点将会在时间元组中插入的位置,也就是问候语在问候语元组中的索引。
from bisect import bisect
greetings = ('深夜还在工作,身体和你有仇吗?',
'好好利用清晨的时间'
'上午要努力工作哦,加油。',
'中午来场午休吧。',
'下午脑子易疲劳,干点轻松的活吧。',
'傍晚了,听听音乐看看书吧。',
'晚上了,身体需要好好休息,请关机。')
breakpoints = [5, 8, 11, 14, 18, 21]
nowhour = datetime.now().hour
index = bisect(breakpoints, nowhour)
greet = greetings[index]
print(greet)
题目3
随机产生50个[60,80]范围内的随机数,统计每个整数出现的次数。
1.对列表元素依次添加和修改
from random import randint
nums = [randint(60, 80) for i in range(50)] # 随机整数序列 # randint左闭右闭
feq = {} # 空字典,不是空集合
# if语句
for i in nums:
if i in feq.keys():
feq[i] += 1
else:
feq[i] = 1
print(feq)
2.不使用if语句:
get方法,如果data在字典,默认data,值+1;data不在字典里,添加键,值为0+1
for data in nums:
feq[data] = feq.get(data, 0)+1
print(nums)
print(feq)
3.count函数:
重复统计,可以不加set()
for data in set(nums):
feq[data] = nums.count(data)
print(feq)
4.导入模块
from collections import Counter
print(Counter(nums))