-
用三个集合表示三门学科的选课学生姓名(一个学生可以同时选多门课)
a. 求选课学生总共有多少人
b. 求只选了第一个学科的人的数量和对应的名字
c. 求只选了一门学科的学生的数量和对应的名字
d. 求只选了两门学科的学生的数量和对应的名字
e. 求选了三门学生的学生的数量和对应的名字
C = {'张三', '李四', '王五', '赵六'} Java = {'王二', '李四', '杨七', '赵六'} Python = {'张三', '赵六', '钱八', '孙九', '王二'} # a. 求选课学生总共有多少人 total = C | Java | Python # {'张三', '王二', '钱八', '杨七', '李四', '赵六', '王五', '孙九'} # count = 0 # for x in total: # count += 1 # print('学生人数:', count) # 方法2 print('学生人数', len(total)) print('------------------------------华丽分割线-----------------------------') # b. 求只选了第一个学科的人的数量和对应的名字 r1 = C - Python - Java print('选了第一个学科的人的数量和对应的名字:', len(C), r1) print('------------------------------华丽分割线-----------------------------') # c. 求只选了一门学科的学生的数量和对应的名字 r = C & Java & Python print('r', r) only_stu = C ^ Java ^ Python - r print('选了一门学科的学生的数量和对应的名字:', len(only_stu), only_stu) 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. 求只选了两门学科的学生的数量和对应的名字 r2 = total - r - only_stu print('只选了两门学科', r2, len(r2)) 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. 求选了三门学生的学生的数量和对应的名字 r3 = C & Python & Java print('三门学科的学生的数量和对应的名字:', len(r3), r3)
-
获取列表中出现次数最多的元素
例如: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 = input('日期:')
year = int(date[0:4])
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)
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)