用三个集合表示三门学科的选课学生姓名(一个学生可以同时选多门课)
a. 求选课学生总共有多少人
b. 求只选了第一个学科的人的数量和对应的名字
c. 求只选了一门学科的学生的数量和对应的名字
d. 求只选了两门学科的学生的数量和对应的名字
e. 求选了三门学生的学生的数量和对应的名字
C = {'张三', '李四', '王五', '赵六'}
Java = {'王二', '李四', '杨七', '赵六'}
Python = {'张三', '赵六', '钱八', '孙九', '王二'}# a. 求选课学生总共有多少人
total = C | Java | Python # {'张三', '王二', '钱八', '杨七', '李四', '赵六', '王五', '孙九'}
count = 0
for x in total:count += 1
print('学生人数:', count)print('------------------------------华丽分割线-----------------------------')# b. 求只选了第一个学科的人的数量和对应的名字
count = 0
for x in C:count += 1print(x)
print('选了第一个学科的人的人数:', count)print('------------------------------华丽分割线-----------------------------')# c. 求只选了一门学科的学生的数量和对应的名字
# only_stu = C ^ Java ^ Python
# print('选了一门学科的学生:', only_stu)
# count = 0
# for x in only_stu:
# count += 1
# print('选了一门学科的人数:', count)total = C | Java | Python
count = 0
c = []
p = []
j = []
for x in total:if x in C and x not in Java and x not in Python:c.append(x)count += 1# print('只选C:', x)elif x in Java and x not in C and x not in Python:j.append(x)count += 1# print('只选Java:', x)elif x in Python and x not in C and x not in Java:p.append(x)count += 1# print('只选Python:', x)
print('只选C:', c)
print('只选Java:', j)
print('只选Python:', p)
print('选了一门学科的人数:', count)print('------------------------------华丽分割线-----------------------------')# d. 求只选了两门学科的学生的数量和对应的名字
total = C | Java | Python
C_P = []
C_J = []
J_P = []
for x in total:if x in C and x in Java and x not in Python:C_J.append(x)elif x in C and x in Python and x not in Java:C_P.append(x)elif x in Java and x in Python and x not in C:J_P.append(x)
print('选了C和Python的学生:', C_P)
print('选了C和Java的学生:', C_J)
print('选了Java和Python的学生:', J_P)print('------------------------------华丽分割线-----------------------------')# e. 求选了三门学生的学生的数量和对应的名字
print('选了三门学生的学生:', C & Python & Java)
count = 0
for x in C & Python & Java:count += 1
print('选了三门学生的人数:', count)
获取列表中出现次数最多的元素
例如: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]
count1 = []
max1 = []
for index, x in enumerate(nums):count2 = nums.count(x)if index == 0:max1.append(x)count1.append(count2)else:if count1[0] < count2:del count1[0]count1.append(count2)del max1[0]max1.append(x)elif count1[0] == count2:count1.append(count2)max1.append(x)
print(set(max1))
实现给定一个日期,判断这个日期是今年第几天的程序(尝试)
例如:2022/12/31 --> 今年第365天;2022/1/1 --> 今年第1天
date = '2022/12/31'
month = date[5:7]
if month[-1] == '/':month = month[0]
month = int(month)day = date[-2:]
if date[-2] == '/':day = day[-1]
day = int(day)for x in range(1, month+1):if month == 1:print('今年第', day, '天', sep='')breakelif month == 2:print('今年第', 31 + day, '天', sep='')breakelse:if month % 2 == 0:day = 31 + 29 + (month-2)//2 * 30 + (month-2)//2 * 31print('今年第', day, '天', sep='')breakelse:day = 31 + 29 + ((month - 2) // 2) - 1 * 30 + (month - 2) // 2 * 31print('今年第', day, '天', sep='')break