-
用三个集合表示三门学科的选课学生姓名(一个学生可以同时选多门课)
chinese = {'小明', '小莉', '小美', '敏敏', 'lisa', 'Bob', '张三'} math = {'张三', '李四', '王五', '小明', 'lisa', '小美'} english = {'敏敏', '小希', 'Jenny', '刘瑶', '张三', 'Bob'}
a. 求选课学生总共有多少人
all_stu = chinese | math | english print('选课学生总共有多少人:', len(all_stu))
b. 求只选了第一个学科的人的数量和对应的名字
stu1 = chinese - math - english print('只选了第一个学科的人的数量和对应的名字:', len(stu1), stu1)
c. 求只选了一门学科的学生的数量和对应的名字
stu1 = chinese - math - english stu2 = math - chinese - english stu3 = english - chinese - math count1 = len(stu1) + len(stu2) + len(stu3) print('只选了一门学科的学生的数量和对应的名字:', count1, stu1 | stu2 | stu3) # 利用对称差集 result = chinese ^ math ^ english - chinese & math & english print('只选了一门学科的学生的数量和对应的名字:', len(result), result)
d. 求只选了两门学科的学生的数量和对应的名字
chi_math_eng = chinese & math & english chi_math = chinese & math - chi_math_eng chi_eng = chinese & english - chi_math_eng math_eng = math & english - chi_math_eng count2 = len(chi_math) + len(chi_eng) + len(math_eng) print('只选了两门学科的学生的数量和对应的名字:', count2, chi_math | chi_eng | math_eng)
e. 求选了三门学生的学生的数量和对应的名字
chi_math_eng = chinese & math & english print('选了三门学生的学生的数量和对应的名字:', len(chi_math_eng), chi_math_eng)
-
获取列表中出现次数最多的元素
例如:nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> 打印:3
nums = [1,2,2,1,3] --> 打印1、2
nums = [1,2,2,1,3] max_count = 0 content = [] for x in set(nums): if max_count < nums.count(x): max_count = nums.count(x) content.clear() content.append(x) elif max_count == nums.count(x): content.append(x) print('列表中出现次数最多的元素:', content) # 方法2 # 1)去重获取不重复的元素 new_nums = list(set(nums)) # 2)统计每个元素出现的次数 counts = [] for x in new_nums: counts.append(nums.count(x)) # 3)获取最大次数 max_count = max(counts) # 4)获取最大次数对应的元素 for index in range(len(counts)): if counts[index] == max_count: print(new_nums[index])
-
实现给定一个日期,判断这个日期是今年第几天的程序(尝试)
例如:2022/12/31 --> 今年第365天;2022/1/1 --> 今年第1天
date = '2023/03/17'
# 1)提取年月日
year = int(date[0:4])
month = int(date[5:7])
day = int(date[-2:])
# print(year, month, day)
# 2)
"""
1月份:day
2月份:31 + day
3月份:31 + 28/29 + day
"""
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30]
if month == 1:
total_days = day
else:
total_days = sum(days[:month-1]) + day
if month > 2:
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
total_days += 1
print(total_days)