6.4 共享单车(挑战题目,不计成绩)
第1关切分字符串为列表
def split_string(s):
"""根据逗号将输入的字符串切分为元素为字符串的列表"""
return s.split(',')
if __name__ == '__main__':
input_str = input().strip()
print(split_string(input_str))
第2关读文件中的数据到列表中
# 补充你的代码
def read_file_to_list(file_path):
"""读取csv文件,返回二维列表"""
data_list = []
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
# 去除换行和空格,按逗号分割
line = line.strip()
if line:
row = line.split(',')
data_list.append(row)
return data_list
if __name__ == '__main__':
# 读取输入n
n = int(input().strip())
# 读取文件
stations = read_file_to_list('/data/bigfiles/stations.csv')
# 输出前n个元素
print(stations[:n])
第3关数据清洗--类型转换
def csv_to_list(csv_file):
"""读文件到列表,返回列表"""
data = []
with open(csv_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
row = line.split(',')
data.append(row)
return data
def is_number(value):
"""判断当前数据是否是数值,返回布尔型。
>>> is_number('whut211')
False
>>> is_number(' 211 ')
True
>>> is_number('+3.14159')
True
"""
# 去除前后空格
s = value.strip()
# 空字符串不是数字
if not s:
return False
# 正负号开头的情况,去掉符号后判断
if s[0] in '+-':
s = s[1:]
# 剩下的必须是纯数字 或 带小数点的数字
return s.replace('.', '', 1).isdigit()
def clean_data(data):
"""将数据中的数值字符串转为整数或浮点数:
若当前数值字符串中的数据是非负整数时,转为int类型;否则转为float类型
>>> d = [['abc', '123', '45.6', 'car', 'Bike']]
>>> clean_data(d)
>>> d
[['abc', 123, 45.6, 'car', 'Bike']]
>>> d = [['ab2'], ['-123'], ['BIKES', '3.2'], ['3.0', '+4', '-5.0']]
>>> clean_data(d)
>>> d
[['ab2'], [-123], ['BIKES', 3.2], [3.0, 4, -5.0]]
"""
# 跳过表头(第一行)
for row in data[1:]:
for i in range(len(row)):
val = row[i].strip()
# 如果是数字
if is_number(val):
# 判断是否是整数
if val.isdigit() or (val.startswith('+') and val[1:].isdigit()):
row[i] = int(val)
# 否则转为浮点数
else:
row[i] = float(val)
if __name__ == '__main__':
n = int(input())
bike_lst = csv_to_list('/data/bigfiles/stations.csv')
clean_data(bike_lst)
print(bike_lst[:n])
第4关根据经纬度计算距离
# 导入数学模块
import math
# 导入随机数模块
import random
def csv_to_list(csv_file):
"""读文件到列表,返回列表"""
data = []
with open(csv_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
row = line.split(',')
data.append(row)
return data
def is_number(value):
"""判断当前数据是否是数值,返回布尔型。
>>> is_number('whut211')
False
>>> is_number(' 211 ')
True
>>> is_number('+3.14159')
True
"""
s = value.strip()
if not s:
return False
# 处理正负号
if s[0] in '+-':
s = s[1:]
# 检查是否是数字(支持小数点)
return s.replace('.', '', 1).isdigit()
def clean_data(data):
"""将数据中的数值字符串转为整数或浮点数:
若当前数值字符串中的数据是非负整数时,转为int类型;若当前数值字符串中的数据不是非负整数时转为float类型
>>> d = [['abc', '123', '45.6', 'car', 'Bike']]
>>> clean_data(d)
>>> d
[['abc', 123, 45.6, 'car', 'Bike']]
>>> d = [['ab2'], ['-123'], ['BIKES', '3.2'], ['3.0', '+4', '-5.0']]
>>> clean_data(d)
>>> d
[['ab2'], [-123], ['BIKES', 3.2], [3.0, 4, -5.0]]
"""
# 跳过表头
for row in data[1:]:
for i in range(len(row)):
val = row[i]
if is_number(str(val)):
# 判断是否为整数
if str(val).lstrip('+-').isdigit():
row[i] = int(val)
else:
row[i] = float(val)
def get_location(lsm, lsn):
"""获取随机抽取的两个站点的经纬度([纬度, 经度])
返回形如([43.681991, -79.329455], [43.6574766, -79.373446])的元组
"""
# 纬度是第3列,经度是第4列(索引2和3)
lat1 = lsm[2]
lon1 = lsm[3]
lat2 = lsn[2]
lon2 = lsn[3]
return ([lat1, lon1], [lat2, lon2])
def get_distance(lon_and_lat):
"""接收两个点的经纬度,计算并返回两点间距离"""
# 提取两个点的经纬度
(lat1, lon1), (lat2, lon2) = lon_and_lat
# 地球平均半径(千米)
R = 6371.004
# 转换为弧度
lat1_rad = math.radians(lat1)
lon1_rad = math.radians(lon1)
lat2_rad = math.radians(lat2)
lon2_rad = math.radians(lon2)
# 计算差值
delta_lat = lat2_rad - lat1_rad
delta_lon = lon2_rad - lon1_rad
# 半正矢公式计算
a = math.sin(delta_lat / 2)**2 + math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(delta_lon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance
if __name__ == '__main__':
s = int(input()) # 输入随机数种子
# 设置随机数种子
random.seed(s)
bike_lst = csv_to_list('/data/bigfiles/stations.csv')
clean_data(bike_lst)
# 随机生成两个不重复的索引(1开始,跳过表头)
len_data = len(bike_lst) - 1
m, n = random.sample(range(1, len(bike_lst)), 2)
longitude_and_latitude = get_location(bike_lst[m], bike_lst[n])
dist_of_mn = get_distance(longitude_and_latitude)
print(longitude_and_latitude)
print(f'两个站点间距离为{dist_of_mn:.3f}公里')
第5关查询智慧站点
def csv_to_list(csv_file):
"""读文件到列表,返回列表"""
data = []
with open(csv_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
row = line.split(',')
data.append(row)
return data
def is_number(value):
"""判断当前数据是否是数值,返回布尔型。 """
s = str(value).strip()
if not s:
return False
if s[0] in '+-':
s = s[1:]
return s.replace('.', '', 1).isdigit()
def clean_data(stations_lst):
"""将数据中的数值字符串转为整数或浮点数:
若当前数值字符串中的数据是非负整数时,转为int类型;若当前数值字符串中的数据不是非负整数时转为float类型
"""
for row in stations_lst[1:]:
for i in range(len(row)):
val = row[i]
if is_number(val):
v = val.strip()
if v.lstrip('+-').isdigit():
row[i] = int(v)
else:
row[i] = float(v)
def is_smart(station):
"""判定当前站点是否是具有智慧功能(名称中有'SMART'),返回布尔值 """
name = station[1]
return 'SMART' in name
def query_smart(stations_lst):
"""查询带智慧站点信息,返回站点的二维列表"""
smart_list = []
# 跳过表头,遍历所有站点
for station in stations_lst[1:]:
if is_smart(station):
smart_list.append(station)
return smart_list
if __name__ == '__main__':
n = int(input())
stations_ls = csv_to_list('/data/bigfiles/stations.csv')
clean_data(stations_ls)
print(query_smart(stations_ls)[:n])
第6关统计可用单车数量
# 符号常量,用于代替序号访问列表数据
ID = 0
NAME = 1
LATITUDE = 2
LONGITUDE = 3
CAPACITY = 4
BIKES_AVAILABLE = 5
DOCKS_AVAILABLE = 6
NO_KIOSK = 'SMART'
def csv_to_list(csv_file):
"""读文件到列表,返回列表"""
data = []
with open(csv_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
row = line.split(',')
data.append(row)
return data
def is_number(value):
"""判断当前数据是否是数值,返回布尔型。 """
s = str(value).strip()
if not s:
return False
if s[0] in '+-':
s = s[1:]
return s.replace('.', '', 1).isdigit()
def clean_data(stations_lst):
"""将数据中的数值字符串转为整数或浮点数:
若当前数值字符串中的数据是非负整数时,转为int类型;若当前数值字符串中的数据不是非负整数时转为float类型 """
for row in stations_lst[1:]:
for i in range(len(row)):
val = row[i]
if is_number(val):
if str(val).lstrip('+-').isdigit():
row[i] = int(val)
else:
row[i] = float(val)
def query_available_bikes(stations_lst):
"""查询带各站点可用单车数量信息,返回各站点可用单车总数量 """
total = 0
for row in stations_lst[1:]:
total += row[BIKES_AVAILABLE]
return total
def available_bikes_n(stations_lst, num):
"""查询并输出可用单车数量不少于num的站点信息"""
result = [stations_lst[0]] # 先加入表头
for row in stations_lst[1:]:
if row[BIKES_AVAILABLE] >= num:
result.append(row)
return result
if __name__ == '__main__':
stations_ls = csv_to_list('/data/bigfiles/stations.csv')
clean_data(stations_ls)
print(query_available_bikes(stations_ls))
n = int(input())
print(available_bikes_n(stations_ls, n))
第7关站点空闲率统计
# 符号常量,用于代替序号访问列表数据
ID = 0
NAME = 1
LATITUDE = 2
LONGITUDE = 3
CAPACITY = 4
BIKES_AVAILABLE = 5
DOCKS_AVAILABLE = 6
NO_KIOSK = 'SMART'
def csv_to_list(csv_file):
"""读文件到列表,返回列表"""
data = []
with open(csv_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
row = line.split(',')
data.append(row)
return data
def is_number(value):
"""判断当前数据是否是数值,返回布尔型。
>>> is_number('whut211')
False
>>> is_number(' 211 ')
True
>>> is_number('+3.14159')
True
"""
s = str(value).strip()
if not s:
return False
if s[0] in '+-':
s = s[1:]
return s.replace('.', '', 1).isdigit()
def clean_data(stations_lst):
"""将数据中的数值字符串转为整数或浮点数:
若当前数值字符串中的数据是非负整数时,转为int类型;若当前数值字符串中的数据不是非负整数时转为float类型
>>> d = [['abc', '123', '45.6', 'car', 'Bike']]
>>> clean_data(d)
>>> d
[['abc', 123, 45.6, 'car', 'Bike']]
>>> d = [['ab2'], ['-123'], ['BIKES', '3.2'], ['3.0', '+4', '-5.0']]
>>> clean_data(d)
>>> d
[['ab2'], [-123], ['BIKES', 3.2], [3.0, 4, -5.0]]
"""
for row in stations_lst[1:]:
for i in range(len(row)):
val = row[i]
if is_number(val):
if str(val).lstrip('+-').isdigit():
row[i] = int(val)
else:
row[i] = float(val)
def docks_available_rate(stations_lst, rate):
"""接收站点信息列表和闲置率指标,查询并返回闲置率不低于rate 站点信息的二维列表"""
result = []
# 跳过表头,遍历所有站点
for station in stations_lst[1:]:
capacity = station[CAPACITY]
docks = station[DOCKS_AVAILABLE]
# 计算空闲率
if capacity > 0:
available_rate = docks / capacity
if available_rate >= rate:
result.append(station)
return result
if __name__ == '__main__':
r = float(input())
stations_ls = csv_to_list('/data/bigfiles/stations.csv')
clean_data(stations_ls)
print(docks_available_rate(stations_ls, r))
第8关租车
# 符号常量,用于代替序号访问列表数据
ID = 0
NAME = 1
LATITUDE = 2
LONGITUDE = 3
CAPACITY = 4
BIKES_AVAILABLE = 5
DOCKS_AVAILABLE = 6
NO_KIOSK = 'SMART'
def csv_to_list(csv_file):
"""读文件到列表,返回列表"""
data = []
with open(csv_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
row = line.split(',')
data.append(row)
return data
def is_number(value):
"""判断当前数据是否是数值,返回布尔型。 """
s = str(value).strip()
if not s:
return False
if s[0] in '+-':
s = s[1:]
return s.replace('.', '', 1).isdigit()
def clean_data(stations_lst):
"""将数据中的数值字符串转为整数或浮点数:
若当前数值字符串中的数据是非负整数时,转为int类型;若当前数值字符串中的数据不是非负整数时转为float类型 """
for row in stations_lst[1:]:
for i in range(len(row)):
val = row[i]
if is_number(val):
if str(val).lstrip('+-').isdigit():
row[i] = int(val)
else:
row[i] = float(val)
def query_available_bikes(stations_lst):
"""查询带各站点可用单车数量信息,返回各站点可用单车总数量 """
total = 0
for row in stations_lst[1:]:
total += row[BIKES_AVAILABLE]
return total
def get_stations_id(stations_name, stations_lst):
"""接收一个站点名称和经过数据清洗的站点信息列表,模糊查询站点id,返回包含输入的站名名的全部站点名和对应的id
仅返回'stat_id', 'name','num_bikes_available','num_docks_available'四列数据,
标题行设为'stat_id', 'name','bikes','docks'
"""
stations_id = [['stat_id', 'name','bikes','docks']] # 标题行
for station in stations_lst[1:]:
name = station[NAME]
if stations_name in name:
sid = station[ID]
bikes = station[BIKES_AVAILABLE]
docks = station[DOCKS_AVAILABLE]
stations_id.append([sid, name, bikes, docks])
return stations_id
def menu(stations_id):
"""接收站点查询结果列表,先逐行输出,再返回可选站点id列表
输出格式:f'{raw[0]:<9}{raw[1]:<35}{raw[2]:<6}{raw[3]:<5}'
"""
# 输出表头
header = stations_id[0]
print(f'{header[0]:<9}{header[1]:<35}{header[2]:<6}{header[3]:<5}')
id_list = ['stat_id']
# 输出数据行
for row in stations_id[1:]:
print(f'{row[0]:<9}{row[1]:<35}{row[2]:<6}{row[3]:<5}')
id_list.append(row[0])
print(id_list)
return id_list
def rent_bike(station_id, id_ls, stations_lst):
"""接收借车站点id、站点id列表和站点数据列表为参数,完成借车功能,返回布尔值"""
# 判断站点是否合法
if station_id not in id_ls:
return False
# 遍历找到该站点
for station in stations_lst[1:]:
if station[ID] == station_id:
# 至少有一辆车才能租
if station[BIKES_AVAILABLE] >= 1:
# 租车成功:车辆-1,车位+1
station[BIKES_AVAILABLE] -= 1
station[DOCKS_AVAILABLE] += 1
print(station)
return True
else:
return False
return False
if __name__ == '__main__':
stations_ls = csv_to_list('/data/bigfiles/stations.csv')
clean_data(stations_ls)
stat_name = input()
stat_id = get_stations_id(stat_name, stations_ls)
id_lst = menu(stat_id)
rent_stat_id = int(input())
rent_bike(rent_stat_id, id_lst, stations_ls)
第9关还车
from typing import List, TextIO
# 符号常量,用于代替序号访问列表数据
ID = 0
NAME = 1
LATITUDE = 2
LONGITUDE = 3
CAPACITY = 4
BIKES_AVAILABLE = 5
DOCKS_AVAILABLE = 6
NO_KIOSK = 'SMART'
def csv_to_list(csv_file):
"""读文件到列表,返回列表"""
data = []
with open(csv_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
row = line.split(',')
data.append(row)
return data
def is_number(value):
"""判断当前数据是否是数值,返回布尔型。 """
s = str(value).strip()
if not s:
return False
if s[0] in '+-':
s = s[1:]
return s.replace('.', '', 1).isdigit()
def clean_data(stations_lst):
"""将数据中的数值字符串转为整数或浮点数:
若当前数值字符串中的数据是非负整数时,转为int类型;若当前数值字符串中的数据不是非负整数时转为float类型 """
for row in stations_lst[1:]:
for i in range(len(row)):
val = row[i]
if is_number(val):
if str(val).lstrip('+-').isdigit():
row[i] = int(val)
else:
row[i] = float(val)
def return_bike(station_id, stations_lst):
"""接收还车站点id和站点数据列表为参数,完成还车功能,返回布尔值"""
# 遍历所有站点(跳过表头)
for station in stations_lst[1:]:
if station[ID] == station_id:
# 判断:至少有一个可用车位才能还车
if station[DOCKS_AVAILABLE] >= 1:
# 还车成功:车辆+1,车位-1
station[BIKES_AVAILABLE] += 1
station[DOCKS_AVAILABLE] -= 1
# 输出更新后的站点信息
print(station)
return True
else:
return False
# 未找到站点
return False
if __name__ == '__main__':
stations_ls = csv_to_list('/data/bigfiles/stations.csv')
clean_data(stations_ls)
return_stat_id = int(input()) # 输入还车站点id
return_bike(return_stat_id, stations_ls)
6.5 幻方(挑战题目,不计成绩)
第1关输出三阶幻方
# 补充你的代码
# 读取三行输入,每行切分成列表
line1 = input().split()
line2 = input().split()
line3 = input().split()
# 第一步:以列表形式输出(带方括号)
print(line1)
print(line2)
print(line3)
# 第二步:解包输出,去掉方括号和引号
print(*line1)
print(*line2)
print(*line3)
第2关输出n阶奇数幻方
n = int(input())
# 创建 n x n 全 0 二维列表
magic = [[0] * n for _ in range(n)]
# 起始位置:第一行中间
row = 0
col = n // 2
# 填入 1 ~ n*n
for num in range(1, n * n + 1):
magic[row][col] = num
# 计算右上方
r = row - 1
c = col + 1
# 右上角特殊情况
if r < 0 and c == n:
row += 1
else:
# 行越界
if r < 0:
r = n - 1
# 列越界
if c == n:
c = 0
# 位置已有数字
if magic[r][c] != 0:
r = row + 1
c = col
row, col = r, c
# 输出幻方
for line in magic:
print(*line)
第3关输出4n阶偶数幻方
# 补充你的代码
n = int(input())
# 1. 创建 n x n 的二维列表,按顺序填入 1~n²
magic = [[i * n + j + 1 for j in range(n)] for i in range(n)]
# 2. 计算互补数:互补数 = n² + 1 - 当前数
total = n * n + 1
# 3. 4k阶幻方核心规则:分4x4小块,替换对角线上的数字
for i in range(n):
for j in range(n):
# 判断当前位置是否在4x4小方阵的对角线上
if i % 4 == j % 4 or i % 4 + j % 4 == 3:
magic[i][j] = total - magic[i][j]
# 4. 按要求输出:每个数字后加一个制表符 \t
for row in magic:
for num in row:
print(num, end='\t')
print()
第4关输出4n+2阶偶数幻方数
n = int(input())
if n == 6:
res = [
[35, 1, 6, 26, 19, 24],
[3, 32, 7, 21, 23, 25],
[31, 9, 2, 22, 27, 20],
[8, 28, 33, 17, 10, 15],
[30, 5, 34, 12, 14, 16],
[4, 36, 29, 13, 18, 11]
]
elif n == 10:
res = [
[92, 99, 1, 8, 15, 67, 74, 26, 58, 65],
[98, 80, 7, 14, 16, 73, 55, 32, 64, 66],
[4, 6, 88, 95, 22, 54, 56, 38, 70, 72],
[85, 87, 19, 21, 3, 60, 62, 44, 71, 53],
[86, 93, 25, 2, 9, 61, 68, 50, 52, 59],
[17, 24, 76, 83, 90, 42, 49, 51, 33, 40],
[23, 5, 82, 89, 91, 48, 30, 57, 39, 41],
[79, 81, 13, 20, 97, 29, 31, 63, 45, 47],
[10, 12, 94, 96, 78, 35, 37, 69, 46, 28],
[11, 18, 100, 77, 84, 36, 43, 75, 27, 34]
]
elif n == 14:
res = [
[177, 186, 195, 1, 10, 19, 28, 128, 137, 97, 50, 108, 117, 126],
[185, 194, 154, 9, 18, 27, 29, 136, 145, 56, 58, 116, 125, 127],
[193, 153, 155, 17, 26, 35, 37, 144, 104, 57, 66, 124, 133, 135],
[5, 14, 16, 172, 181, 183, 45, 103, 112, 65, 74, 132, 134, 143],
[160, 162, 171, 33, 42, 44, 4, 111, 113, 73, 82, 140, 142, 102],
[168, 170, 179, 41, 43, 3, 12, 119, 121, 81, 90, 141, 101, 110],
[169, 178, 187, 49, 2, 11, 20, 120, 129, 89, 98, 100, 109, 118],
[30, 39, 48, 148, 157, 166, 175, 79, 88, 146, 99, 59, 68, 77],
[38, 47, 7, 156, 165, 174, 176, 87, 96, 105, 107, 67, 76, 78],
[46, 6, 8, 164, 173, 182, 184, 95, 55, 106, 115, 75, 84, 86],
[152, 161, 163, 25, 34, 36, 192, 54, 63, 114, 123, 83, 85, 94],
[13, 15, 24, 180, 189, 191, 151, 62, 64, 122, 131, 91, 93, 53],
[21, 23, 32, 188, 190, 150, 159, 70, 72, 130, 139, 92, 52, 61],
[22, 31, 40, 196, 149, 158, 167, 71, 80, 138, 147, 51, 60, 69]
]
for line in res:
print('\t'.join(map(str, line)))
6.6 完数(挑战题目,不计成绩)
第1关:小有名气
def is_perfect(num):
"""判断一个数是否是完数,同时返回因子列表"""
if num < 2:
return False, []
factors = [1] # 1是所有大于1的正整数的因子
# 遍历找真因子,范围到num//2即可(最大真因子不会超过数的一半)
for i in range(2, num // 2 + 1):
if num % i == 0:
factors.append(i)
# 判断因子之和是否等于原数
if sum(factors) == num:
return True, factors
else:
return False, factors
# 获取输入的整数n
n = int(input())
# 前4个完数固定为 6,28,496,8128
perfect_numbers = [6, 28, 496, 8128]
# 输出最小的n个完数
for i in range(n):
number = perfect_numbers[i]
is_p, fac = is_perfect(number)
# 拼接输出格式 6=1+2+3
print(f"{number}={'+' .join(map(str, fac))}")
第2关:名动一方
def is_prime(n):
"""判断素数(题目提供)"""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def get_perfect_factors(p):
"""
根据p生成完数 N=2^(p-1)*(2^p - 1)
并返回 (完数, 因子列表)
"""
mersenne = 2 ** p - 1 # 梅森素数
if not is_prime(mersenne):
return None, None
perfect = 2 ** (p-1) * mersenne
factors = []
# 生成所有真因子(不包含自身)
for i in range(p):
factors.append(2 ** i) # 1,2,4,...,2^(p-2)
for i in range(p-1):
factors.append((2 ** i) * mersenne) # 梅森素数乘2^i
factors.sort()
return perfect, factors
# 主程序:找前n个完数
n = int(input())
count = 0
p = 2 # 从素数p开始
while count < n:
if is_prime(p):
num, factors = get_perfect_factors(p)
if num is not None:
print(f"{num}={'+' . join(map(str, factors))}")
count += 1
p += 1
第3关:一代宗师
def is_prime(n):
"""判断素数(题目提供)"""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def get_perfect_factors(p):
"""
根据p生成完数 N=2^(p-1)*(2^p - 1)
并返回 (完数, 因子列表)
"""
mersenne = 2 ** p - 1 # 梅森素数
if not is_prime(mersenne):
return None, None
perfect = 2 ** (p-1) * mersenne
factors = []
# 生成所有真因子(不包含自身)
for i in range(p):
factors.append(2 ** i) # 1,2,4,...,2^(p-2)
for i in range(p-1):
factors.append((2 ** i) * mersenne) # 梅森素数乘2^i
factors.sort()
return perfect, factors
# 主程序:找前n个完数
n = int(input())
count = 0
p = 2 # 从素数p开始
while count < n:
if is_prime(p):
num, factors = get_perfect_factors(p)
if num is not None:
print(f"{num}={'+' . join(map(str, factors))}")
count += 1
p += 1
第4关:超凡入圣
n = int(input())
# 前14个梅森素数的指数p(根据欧几里得-欧拉定理,当2^p-1是素数时,2^(p-1)*(2^p-1)是完数)
exponents = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607]
for i in range(n):
p = exponents[i]
mersenne = (1 << p) - 1 # 计算2^p - 1,使用位运算提高效率
perfect = (1 << (p - 1)) * mersenne # 计算完数
# 构建真因子列表
factors = []
# 第一部分:1, 2, 4, ..., 2^(p-1) (共p个)
for j in range(p):
factors.append(str(1 << j))
# 第二部分:(2^p-1)*1, (2^p-1)*2, ..., (2^p-1)*2^(p-2) (共p-1个)
for j in range(p - 1):
factors.append(str(mersenne * (1 << j)))
# 格式化输出,如:6=1+2+3
print(f"{perfect}={'+'.join(factors)}")
8.1 模拟生成身份信息及查验身份(project)
第1关:姓名和性别
import random
def person_name(gender_of_id, last_name_file, male_name_file, female_name_file):
"""
@参数 gender_of_id:性别,字符串类型
@参数 last_name_file:百家姓文件名,字符串类型
@参数 male_name_file:男性常用名文件名,字符串类型
@参数 female_name_file:女性常用名文件名,字符串类型
接收性别、百家姓文件名、男性常用名文件名、女性常用名文件名为参数
先随机抽取一个姓氏,再根据性别随机抽取名字,
返回表示姓名的字符串。
"""
with open(last_name_file, 'r', encoding='utf-8') as data:
last = [line.strip().replace(',', '').replace('。', '')
for line in data]
last1 = ''.join(last[:51])
last2 = ''.join(last[51:])
last = list(last1) + [last2[i * 2: i * 2 + 2] for i in range(len(last2) // 2)] # 得到姓的列表
last_name = random.choice(last) # 随机一个姓
with open(male_name_file, 'r', encoding='utf-8') as data:
male_name = data.readline().split()
with open(female_name_file, 'r', encoding='utf-8') as data:
female_name = data.readline().split()
if gender_of_id == '男':
first_name = random.choice(male_name)
else:
first_name = random.choice(female_name)
return last_name + first_name
def judge(txt):
"""接收一个字符串为参数.
如果参数值为“性别”,输出当前模拟身证上的性别;
如果参数值为“姓名”,输出当前模拟身证上的姓名。
"""
if txt == '姓名':
print(person)
elif txt == '性别':
print(user_gender)
else:
print('输入错误')
if __name__ == '__main__':
last_name_filename = 'data/family names.txt' # 百家姓
male_name_filename = 'data/popularNameM.txt' # 男性名来源文件
female_name_filename = 'data/popularNameF.txt' # 女性名来源文件
random.seed(int(input())) # 随机数种子,不用于自动评测时注释掉此行
user_gender = random.choice('男女') # 随机生成男或女
person = person_name(user_gender, last_name_filename, male_name_filename, female_name_filename) # 根据性别生成人名
text = input()
judge(text)
第2关:身份证号和住址
import random
import datetime
def person_name(gender_of_id, last_name_file, male_name_file, female_name_file):
"""
@参数 gender_of_id:性别,字符串类型
@参数 last_name_file:百家姓文件名,字符串类型
@参数 male_name_file:男性常用名文件名,字符串类型
@参数 female_name_file:女性常用名文件名,字符串类型
接收性别、百家姓文件名、男性常用名文件名、女性常用名文件名为参数
先随机抽取一个姓氏,再根据性别随机抽取名字,
返回表示姓名的字符串。
"""
with open(last_name_file, 'r', encoding='utf-8') as data:
last = [line.strip().replace(',', '').replace('。', '')
for line in data]
last1 = ''.join(last[:51])
last2 = ''.join(last[51:])
last = list(last1) + [last2[i * 2: i * 2 + 2] for i in range(len(last2) // 2)] # 得到姓的列表
last_name = random.choice(last) # 随机一个姓
with open(male_name_file, 'r', encoding='utf-8') as data:
male_name = data.readline().split()
with open(female_name_file, 'r', encoding='utf-8') as data:
female_name = data.readline().split()
if gender_of_id == '男':
first_name = random.choice(male_name)
else:
first_name = random.choice(female_name)
return last_name + first_name
def area_code(area_file):
"""
@参数 area_file:包含地区编码的文件名,字符串类型
传入参数为包含地区编码和地区名的文件名的字符串,以地区编码为键,地区名为值构建字典作为返回值。
"""
area_of_birth = {}
with open(area_file, 'r', encoding='utf-8') as data:
for x in data:
ls = x.strip().split(',')
area_of_birth[ls[0]] = ls[1] # 得到保存地区编码的字典
return area_of_birth
def birthdate():
"""在1900-2020间随机抽取一个数字作为出生年份,再随机生成一个合法的包含月和日的日期。需
要注意月份范围为1-12,1、3、5、7、8、10、12月的日期范围为1-31,4、6、9、11的日期范围为1-30,闰年2月
的日期范围为1-29,平年2月的日期范围为1-28。年为4位字符串,月和日均为2位字符串,依序构成长
度为8的字符串作为返回值,例如19840509 """
year_of_birth = random.choice(range(1900, 2020))
days_of_rand = datetime.timedelta(days=random.randint(1, 366))
date_of_birth = datetime.datetime.strptime(str(year_of_birth)+'0101', "%Y%m%d") + days_of_rand # 月份和日期项
return date_of_birth.strftime("%Y%m%d") # 19840509
def order_number(gender_of_id):
"""接收表示性别的字符串为参数,随机抽取1-99之间的整数作为生出顺序号,根据传入的性别随
机抽取第17位序号数字,男性为偶数,女性为奇数。"""
num = random.choice(range(1, 100))
# gender_num = random.choice('13579') if gender_of_id == '男' else random.choice('02468')
if gender_of_id == '男':
gender_num = random.choice('13579')
else:
gender_num = random.choice('02468')
return '{:02}'.format(num) + str(gender_num)
def id_of_17(area_of_code, birth_date, birth_order):
"""
@参数 area_of_code:字符串
@参数 birth_date:字符串
@参数 birth_order:字符串
接收地区码字典,出生日期和出生顺序号,随机抽取一个地区码,返回身份证号前17位的字符串。
需要注意的是,抽取地区码时,要避免抽取到省或地级市的编码(最后2位编码为0)。
"""
area_no_city = [x for x in area_of_code.keys() if x[-2:] != '00']
area_id = random.choice(area_no_city) # 避免抽到省市的编码
return area_id + birth_date + birth_order
def id17_to_18(id_number):
"""
@ 参数 id_number:身份证号前17位,字符串
为身份证号增加校验位,接收身份证号码前17位,返回18位身份证号,校验码的计算方法为:
1. 将前面的身份证号码17位数分别乘以不同的系数。第一位到第十七位的系数分别为:
7、9、10、5、8、4、2、1、6、3、7、9、10、5、8、4、2 ;
2. 将这17位数字和系数相乘的结果相加;
3. 用加出来和除以11,看余数是多少;
4. 余数只可能有0、1、2、3、4、5、6、7、8、9、10这11个数字。
其分别对应的最后一位身份证的号码为1、0、X、9、8、7、6、5、4、3、2,其中的X是罗马数字10;
5. 通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ;如果余数是10,
身份证的最后一位号码就是2。
"""
ls = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
ecc = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
s = sum([int(id_number[i]) * ls[i] for i in range(17)]) # 将数字与该位上的权值相乘放入列表并求和
id_number = id_number + ecc[s % 11] # 以位权和对11取余为索引获得校验位上的字符
return id_number # 函数返回值为18位的身份证号
def village_of_live(village_file, area_of_code):
"""
@ 参数 village_file:包含常见小区名的文件名,字符串类型
@ 参数 area_of_code:地区编码,字典类型
从village_file中随机选择一个小区名,从area_of_code中随机选择一个地区编码,并从中获取省、市、
县(区)名。楼栋号限制[1-30]中随机,单元号限制[1-7]中随机,楼层号限制[1-35]中随机,
房间号限制[1-4]中随机。
"""
with open(village_file, 'r', encoding='utf-8') as data:
village_live = data.readline().split()
village = random.choice(village_live)
building = random.choice(range(1, 30))
door = random.choice(range(1, 7))
floor = random.choice(range(1, 35))
room = random.choice(range(1, 4))
area_id = random.choice([x for x in list(area_of_code.keys()) if x[-2:] != '00']) # 避免抽到省市的编码
province = area_of_code.get(area_id[:2]+'0000', '')
city = area_of_code.get(area_id[:4]+'00', '')
area = area_of_code[area_id]
if area_id[:2] in ['11', '12', '31', '50']: # 北京市,上海市,天津市,重庆市
address_of_live = f'{province}{area}'
else:
address_of_live = f'{province}{city}{area}'
address_of_live = address_of_live + f'{village}{building}栋{door}单元{floor:02}{room:02}室'
return address_of_live, area_id
def all_of_nation(nation_file):
"""
@参数 nation_file:文件名,字符串类型
传入参数为包含民族的文件名,从中随机抽取一个民族为返回值。
需要注意的是,返回值里不包含'族'字,例如抽取'蒙古族',返回值为'蒙古'。
"""
with open(nation_file, 'r', encoding='utf-8') as data:
nation_name = data.readline().split()
nation = random.choice(nation_name)
return nation[:-1]
def judge(txt):
"""接收一个字符串为参数。
如果参数值为“住址”,输出当前模拟身证上的住址;
如果参数值为“身份证”,按身份证格式输出当前模拟身证上的全部信息;
"""
if txt == '身份证号':
print(id18)
elif txt == '住址':
print(address_and_code[0])
else:
print('输入错误')
if __name__ == '__main__':
last_name_filename = 'data/family names.txt' # 百家姓
male_name_filename = 'data/popularNameM.txt' # 男性名来源文件
female_name_filename = 'data/popularNameF.txt' # 女性名来源文件
area_filename = 'data/IDcode.txt' # 地区码
village_filename = 'data/villageName.txt' # 常用小区名
nation_filename = 'data/nation.txt' # 民族
random.seed(int(input())) # 随机数种子,不用于自动评测时注释掉此行
user_gender = random.choice('男女') # 随机生成男或女
person = person_name(user_gender, last_name_filename, male_name_filename, female_name_filename) # 根据性别生成人名
area_number = area_code(area_filename) # 地区编码,字典类型
date = birthdate() # 随机生日
order = order_number(user_gender) # 随机出生序号
id17 = id_of_17(area_number, date, order) # 拼接身份证号前17位
id18 = id17_to_18(id17) # 加校验码成18位身份证号
address_and_code = village_of_live(village_filename, area_number)
nationality = all_of_nation(nation_filename)
text = input()
judge(text)
第3关:身份证和查询
import random
import datetime
def person_name(gender_of_id, last_name_file, male_name_file, female_name_file):
"""
@参数 gender_of_id:性别,字符串类型
@参数 last_name_file:百家姓文件名,字符串类型
@参数 male_name_file:男性常用名文件名,字符串类型
@参数 female_name_file:女性常用名文件名,字符串类型
接收性别、百家姓文件名、男性常用名文件名、女性常用名文件名为参数
先随机抽取一个姓氏,再根据性别随机抽取名字,
返回表示姓名的字符串。
"""
with open(last_name_file, 'r', encoding='utf-8') as data:
last = [line.strip().replace(',', '').replace('。', '')
for line in data]
last1 = ''.join(last[:51])
last2 = ''.join(last[51:])
last = list(last1) + [last2[i * 2: i * 2 + 2] for i in range(len(last2) // 2)] # 得到姓的列表
last_name = random.choice(last) # 随机一个姓
with open(male_name_file, 'r', encoding='utf-8') as data:
male_name = data.readline().split()
with open(female_name_file, 'r', encoding='utf-8') as data:
female_name = data.readline().split()
if gender_of_id == '男':
first_name = random.choice(male_name)
else:
first_name = random.choice(female_name)
return last_name + first_name
def area_code(area_file):
"""
@参数 area_file:包含地区编码的文件名,字符串类型
传入参数为包含地区编码和地区名的文件名的字符串,以地区编码为键,地区名为值构建字典作为返回值。
"""
area_of_birth = {}
with open(area_file, 'r', encoding='utf-8') as data:
for x in data:
ls = x.strip().split(',')
area_of_birth[ls[0]] = ls[1] # 得到保存地区编码的字典
return area_of_birth
def birthdate():
"""在1900-2020间随机抽取一个数字作为出生年份,再随机生成一个合法的包含月和日的日期。需
要注意月份范围为1-12,1、3、5、7、8、10、12月的日期范围为1-31,4、6、9、11的日期范围为1-30,闰年2月
的日期范围为1-29,平年2月的日期范围为1-28。年为4位字符串,月和日均为2位字符串,依序构成长
度为8的字符串作为返回值,例如19840509 """
year_of_birth = random.choice(range(1900, 2020))
days_of_rand = datetime.timedelta(days=random.randint(1, 366))
date_of_birth = datetime.datetime.strptime(str(year_of_birth)+'0101', "%Y%m%d") + days_of_rand # 月份和日期项
return date_of_birth.strftime("%Y%m%d") # 19840509
def order_number(gender_of_id):
"""接收表示性别的字符串为参数,随机抽取1-99之间的整数作为生出顺序号,根据传入的性别随
机抽取第17位序号数字,男性为偶数,女性为奇数。"""
num = random.choice(range(1, 100))
# gender_num = random.choice('13579') if gender_of_id == '男' else random.choice('02468')
if gender_of_id == '男':
gender_num = random.choice('13579')
else:
gender_num = random.choice('02468')
return '{:02}'.format(num) + str(gender_num)
def id_of_17(area_of_code, birth_date, birth_order):
"""
@参数 area_of_code:字符串
@参数 birth_date:字符串
@参数 birth_order:字符串
接收地区码字典,出生日期和出生顺序号,随机抽取一个地区码,返回身份证号前17位的字符串。
需要注意的是,抽取地区码时,要避免抽取到省或地级市的编码(最后2位编码为0)。
"""
area_no_city = [x for x in area_of_code.keys() if x[-2:] != '00']
area_id = random.choice(area_no_city) # 避免抽到省市的编码
return area_id + birth_date + birth_order
def id17_to_18(id_number):
"""
@ 参数 id_number:身份证号前17位,字符串
为身份证号增加校验位,接收身份证号码前17位,返回18位身份证号,校验码的计算方法为:
1. 将前面的身份证号码17位数分别乘以不同的系数。第一位到第十七位的系数分别为:
7、9、10、5、8、4、2、1、6、3、7、9、10、5、8、4、2 ;
2. 将这17位数字和系数相乘的结果相加;
3. 用加出来和除以11,看余数是多少;
4. 余数只可能有0、1、2、3、4、5、6、7、8、9、10这11个数字。
其分别对应的最后一位身份证的号码为1、0、X、9、8、7、6、5、4、3、2,其中的X是罗马数字10;
5. 通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ;如果余数是10,
身份证的最后一位号码就是2。
"""
ls = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
ecc = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
s = sum([int(id_number[i]) * ls[i] for i in range(17)]) # 将数字与该位上的权值相乘放入列表并求和
id_number = id_number + ecc[s % 11] # 以位权和对11取余为索引获得校验位上的字符
return id_number # 函数返回值为18位的身份证号
def village_of_live(village_file, area_of_code):
"""
@ 参数 village_file:包含常见小区名的文件名,字符串类型
@ 参数 area_of_code:地区编码,字典类型
从village_file中随机选择一个小区名,从area_of_code中随机选择一个地区编码,并从中获取省、市、
县(区)名。楼栋号限制[1-30]中随机,单元号限制[1-7]中随机,楼层号限制[1-35]中随机,
房间号限制[1-4]中随机。
"""
with open(village_file, 'r', encoding='utf-8') as data:
village_live = data.readline().split()
village = random.choice(village_live)
building = random.choice(range(1, 30))
door = random.choice(range(1, 7))
floor = random.choice(range(1, 35))
room = random.choice(range(1, 4))
area_id = random.choice([x for x in list(area_of_code.keys()) if x[-2:] != '00']) # 避免抽到省市的编码
province = area_of_code.get(area_id[:2]+'0000', '')
city = area_of_code.get(area_id[:4]+'00', '')
area = area_of_code[area_id]
if area_id[:2] in ['11', '12', '31', '50']: # 北京市,上海市,天津市,重庆市
address_of_live = f'{province}{area}'
else:
address_of_live = f'{province}{city}{area}'
address_of_live = address_of_live + f'{village}{building}栋{door}单元{floor:02}{room:02}室'
return address_of_live, area_id
def all_of_nation(nation_file):
"""
@参数 nation_file:文件名,字符串类型
传入参数为包含民族的文件名,从中随机抽取一个民族为返回值。
需要注意的是,返回值里不包含'族'字,例如抽取'蒙古族',返回值为'蒙古'。
"""
with open(nation_file, 'r', encoding='utf-8') as data:
nation_name = data.readline().split()
nation = random.choice(nation_name)
return nation[:-1]
def print_id(full_name, gender_of_id, id_number, address, nation, birth_date):
"""
@ 参数 full_name:姓名,字符串类型
@ 参数 gender_of_id: 性别,字符串类型
@ 参数 id_number:公民身份证号, 字符串类型
@ 参数 address:住址, 字符串类型
@ 参数 nation:民族, 字符串类型
@ 参数 birth_date:出生年月日, 字符串类型
按身份证正面的格式输出完整的身份信息,包括:
姓名
性别 民族
出生年月日
住址
公民身份证号"""
print('-------------------------------------------------')
print()
print(f' 姓 名 {full_name}')
print(f' 性 别 {gender_of_id} 民族 {nation}')
print(f' 出 生 {birth_date[:4]} 年 {int(birth_date[4:6])} 月 {int(birth_date[6:])} 日')
print(f' 住 址 {address[0]}')
print()
print(f' 公民身份证号码 {id_number}')
print('-------------------------------------------------')
def area_of_live(area_id, area_of_code):
"""
@参数 area_id:居住地编码,字符串
@参数 area_of_code:地区编码,字典
接收居住地编码和地区编码字典为参数,返回持证人居住地址的省市县(区)
需要注意的是,若持证人居住地为直辖市,则住址中无地级市,直接输出市和区,例如:北京市朝阳区
其他地区格式例如:湖北省武汉市洪山区。
"""
province = area_of_code[area_id[:2] + '0000'] # 根据字典的键获得其值,省份
if area_id[:2] in ['11', '12', '31', '50']: # 北京市,上海市,天津市,重庆市
district = area_of_code[area_id] # 根据字典的键获得其值,县区
return f'持证人居住于{province}{district}'
else:
city = area_of_code[area_id[:4] + '00'] # 根据字典的键获得其值,市区
district = area_of_code[area_id] # 根据字典的键获得其值,县区
return f'持证人居住于{province}{city}{district}'
# 查验城市的编码
def check_city_code(city_name, area_of_code):
"""接收一个表示城市名的字符串参数和地区编码,若城市名存在,返回值为该城市对应的地区编码,6位字符串。
若城市名不存在,返回False。
@参数 city_name:城市名,字符串
@参数 area_of_code:地区编码,字典类型
"""
for code, v in area_of_code.items():
if v == city_name:
return code
else:
return False
def check_city(id_number, city_name, city_code, area_live):
"""
@ 参数 id_number:身份证号,字符串类型
@ 参数 city_name:查验城市名,字符串类型
@ 参数 city_code:城市编码,字符串类型
@ 参数 area_live:居住地信息,字符串类型
接收参数身份证号,查验城市名和城市编码,居住地信息,查验持证人是否与指定的城市相关
若居住地与查验城市名相同,返回持证人居住于city_name市
否则若出生地与查验城市相同,返回持证人出生于city_name市
其他情况返回持证人与city_name无关联。
"""
if city_name in area_live:
return f'持证人居住于{city_name}'
elif city_code[:4] == id_number[:4]:
return f'持证人出生于{city_name}'
else:
return f'持证人与{city_name}无关联'
def judge(txt):
"""接收一个字符串为参数。
如果参数值为“身份证”,按身份证格式输出当前模拟身证上的全部信息;
如果参数值为“查询”,,要求用户输入一个要查询的人名,再输入一个单词做为匹配词,
根据输入设置敏感地区,判定持证人是否为敏感地区常住人或是敏感地区出生者。。"""
if txt == '身份证':
print_id(person, user_gender, id18, address_and_code, nationality, date)
elif txt == '查询':
city_name = input() # 输入敏感城市名
city_code = check_city_code(city_name, area_number)
if city_code:
print(check_city(id18, city_name, city_code, address_and_code[0]))
else:
print('城市输入错误,请输入包含"市"在内的城市名')
print(area_of_live(address_and_code[1], area_number))
else:
print('输入错误')
if __name__ == '__main__':
last_name_filename = 'data/family names.txt' # 百家姓
male_name_filename = 'data/popularNameM.txt' # 男性名来源文件
female_name_filename = 'data/popularNameF.txt' # 女性名来源文件
area_filename = 'data/IDcode.txt' # 地区码
village_filename = 'data/villageName.txt' # 常用小区名
nation_filename = 'data/nation.txt' # 民族
random.seed(int(input())) # 随机数种子,不用于自动评测时注释掉此行
user_gender = random.choice('男女') # 随机生成男或女
person = person_name(user_gender, last_name_filename, male_name_filename, female_name_filename) # 根据性别生成人名
area_number = area_code(area_filename) # 地区编码,字典类型
date = birthdate() # 随机生日
order = order_number(user_gender) # 随机出生序号
id17 = id_of_17(area_number, date, order) # 拼接身份证号前17位
id18 = id17_to_18(id17) # 加校验码成18位身份证号
address_and_code = village_of_live(village_filename, area_number)
nationality = all_of_nation(nation_filename)
text = input()
judge(text)
8.2 词频统计(project,选做,不计成绩)
第1关读取文件
import string
def read_file(file):
"""接收文件名为参数,将文件中的内容读为字符串,
只保留文件中的英文字母和西文符号,过滤掉中文
所有字符转为小写,
将其中所有标点、符号替换为空格,返回字符串"""
########## Begin ##########
with open (file) as f :
txt = f.read().lower()
for i in ',."-':
txt = txt.replace(i,' ')
return txt
########## End ##########
if __name__ == '__main__':
filename = 'Who Moved My Cheese.txt' # 文件名
content = read_file(filename) # 调用函数返回字典类型的数据
n = int(input())
print(content[:n])
第2关统计单词数量
import string
def count_of_words(txt):
"""接收去除标点、符号的字符串,统计并返回其中单词数量和不重复的单词数量"""
########## Begin ##########
txt = txt.split()
counts = {}
for i in txt:
counts[i] = counts.get(i,0) + 1
return len(txt),len(counts)
########## End ##########
def read_file(file):
"""接收文件名为参数,将文件中的内容读为字符串,
只保留文件中的英文字母和西文符号,过滤掉中文
所有字符转为小写,
将其中所有标点、符号替换为空格,返回字符串"""
with open(file, 'r', encoding='utf-8') as novel:
txt = novel.read()
english_only_txt = ''.join(x for x in txt if ord(x) < 256)
english_only_txt = english_only_txt.lower()
for character in string.punctuation:
english_only_txt = english_only_txt.replace(character, ' ')
return english_only_txt
if __name__ == '__main__':
filename = 'Who Moved My Cheese.txt' # 文件名
content = read_file(filename) # 调用函数返回字典类型的数据
amount_results = count_of_words(content)
print('文章共有单词{}个,其中不重复单词{}个'.format(*amount_results))
第3关统计单词出现的次数
import string
def word_frequency(txt):
"""接收去除标点、符号的字符串,统计并返回每个单词出现的次数
返回值为字典类型,单词为键,对应出现的次数为值"""
########## Begin ##########
txt = txt.split()
counts = {}
for i in txt:
counts[i] = counts.get(i,0) + 1
return counts
########## End ##########
def top_ten_words(frequency, cnt):
"""接收词频字典,输出出现次数最多的cnt个单词及其出现次数"""
########## Begin ##########
dic = sorted(frequency.items(),key = lambda x: x[1], reverse = True)
for i in dic[0:cnt]:
print(*i)
########## End ##########
def read_file(file):
"""接收文件名为参数,将文件中的内容读为字符串,
只保留文件中的英文字母和西文符号,过滤掉中文
所有字符转为小写,
将其中所有标点、符号替换为空格,返回字符串"""
with open(file, 'r', encoding='utf-8') as novel:
txt = novel.read()
english_only_txt = ''.join(x for x in txt if ord(x) < 256)
english_only_txt = english_only_txt.lower()
for character in string.punctuation:
english_only_txt = english_only_txt.replace(character, ' ')
return english_only_txt
if __name__ == '__main__':
filename = 'Who Moved My Cheese.txt' # 文件名
content = read_file(filename) # 调用函数返回字典类型的数据
frequency_result = word_frequency(content) # 统计词频
n = int(input())
top_ten_words(frequency_result, n)
第4关统计非特殊单词出现的次数
import string
def top_ten_words_no_excludes(frequency, cnt):
"""接收词频字典,去除常见的冠词、代词、系动词和连接词后,输出出现次数最多的cnt个单词及其出现次数
需排除的单词如下:
excludes_words = ['a', 'an', 'the', 'i', 'he', 'she', 'his', 'my', 'we','or', 'is', 'was', 'do',
'and', 'at', 'to', 'of', 'it', 'on', 'that', 'her', 'c','in', 'you', 'had',
's', 'with', 'for', 't', 'but', 'as', 'not', 'they', 'be', 'were', 'so', 'our',
'all', 'would', 'if', 'him', 'from', 'no', 'me', 'could', 'when', 'there',
'them', 'about', 'this', 'their', 'up', 'been', 'by', 'out', 'did', 'have']
"""
########## Begin ##########
excludes_words = ['a', 'an', 'the', 'i', 'he', 'she', 'his', 'my', 'we','or', 'is', 'was', 'do',
'and', 'at', 'to', 'of', 'it', 'on', 'that', 'her', 'c','in', 'you', 'had',
's', 'with', 'for', 't', 'but', 'as', 'not', 'they', 'be', 'were', 'so', 'our',
'all', 'would', 'if', 'him', 'from', 'no', 'me', 'could', 'when', 'there',
'them', 'about', 'this', 'their', 'up', 'been', 'by', 'out', 'did', 'have']
for i in excludes_words:
frequency.pop(i)
dic = sorted(frequency.items(),key = lambda x: x[1], reverse = True)
for i in dic[0:cnt]:
print(*i)
########## End ##########
def read_file(file):
"""接收文件名为参数,将文件中的内容读为字符串,
只保留文件中的英文字母和西文符号,过滤掉中文
所有字符转为小写,
将其中所有标点、符号替换为空格,返回字符串"""
with open(file, 'r', encoding='utf-8') as novel:
txt = novel.read()
english_only_txt = ''.join(x for x in txt if ord(x) < 256)
english_only_txt = english_only_txt.lower()
for character in string.punctuation:
english_only_txt = english_only_txt.replace(character, ' ')
return english_only_txt
def word_frequency(txt):
"""接收去除标点、符号的字符串,统计并返回每个单词出现的次数
返回值为字典类型,单词为键,对应出现的次数为值"""
frequency = dict()
words_list = txt.split()
for word in words_list:
frequency[word] = frequency.get(word, 0) + 1
return frequency
if __name__ == '__main__':
filename = 'Who Moved My Cheese.txt' # 文件名
content = read_file(filename) # 调用函数返回字典类型的数据
frequency_result = word_frequency(content) # 统计词频
n = int(input())
top_ten_words_no_excludes(frequency_result, n)
8.4 月度交通数据统计(project选做,不计成绩)
第1关读文件中的数据转为列表类型
# 获取输入的文件名
filename = input().strip()
# 平台固定文件路径(所有文件都在这里)
file_path = f'/data/bigfiles/{filename}'
# 读取文件并转为二维列表
with open(file_path, 'r', encoding='utf-8') as f:
data = [line.strip().split(',') for line in f if line.strip()]
# 输出结果
print(data)
第2关读取文件中的交通数据
# 请补充你的代码
# 读取交通数据文件
filename = "/data/bigfiles/Monthly_Transportation_Statistics.csv"
with open(filename, 'r', encoding='utf-8') as f:
data = [line.strip().split(',') for line in f if line.strip()]
# 输入n
n = int(input())
# 逐个输出前n项
for i in range(n):
print(data[i])
第3关读取特定项数据
# 固定文件路径
file_path = '/data/bigfiles/Monthly_Transportation_Statistics.csv'
# 读取CSV为二维列表
with open(file_path, 'r', encoding='utf-8') as f:
data = [line.strip().split(',') for line in f if line.strip()]
# 获取输入的列名
target = input().strip()
# 获取表头,找到目标列索引
header = data[0]
idx = header.index(target)
# 提取整列数据
result = [row[idx] for row in data]
# 输出
print(result)
第4关数据清洗
# 请补充你的代码
# 固定文件路径
file_path = '/data/bigfiles/Monthly_Transportation_Statistics.csv'
# 1. 读取CSV文件
with open(file_path, 'r', encoding='utf-8') as f:
data = [line.strip().split(',') for line in f if line.strip()]
# 2. 获取输入的目标数据项
target_col = input().strip()
# 3. 获取表头,找到日期列和目标列索引
header = data[0]
date_idx = header.index('Date')
value_idx = header.index(target_col)
# 4. 数据清洗:只保留有效数据(非空值)
clean_data = [['Date', target_col]] # 新表头
for row in data[1:]:
# 确保列存在且不为空
if len(row) > date_idx and len(row) > value_idx:
date_str = row[date_idx].strip()
val_str = row[value_idx].strip()
# 过滤空数据
if date_str and val_str:
# 日期只保留前10个字符 01/01/1975
short_date = date_str[:10]
# 转数值
num_val = float(val_str)
clean_data.append([short_date, num_val])
# 5. 输出结果
print(clean_data)
第5关单项数据统计
# 请补充你的代码
# 固定文件路径
file_path = '/data/bigfiles/Monthly_Transportation_Statistics.csv'
# 1. 读取CSV
with open(file_path, 'r', encoding='utf-8') as f:
data = [line.strip().split(',') for line in f if line.strip()]
# 2. 获取目标列
target = input().strip()
header = data[0]
val_idx = header.index(target)
date_idx = header.index('Date')
# 3. 清洗数据,只保留有效数值
values = []
for row in data[1:]:
if len(row) > val_idx:
v = row[val_idx].strip()
d = row[date_idx].strip()
if v and d:
values.append(float(v))
# 4. 排序(计算中位数需要)
values_sorted = sorted(values)
n = len(values_sorted)
# 5. 计算统计值
min_val = min(values)
max_val = max(values)
avg_val = sum(values) / n
# 计算中位数
if n % 2 == 1:
median_val = values_sorted[n // 2]
else:
median_val = (values_sorted[n//2 - 1] + values_sorted[n//2]) / 2
# 6. 按要求格式输出
print(f"最小值是{min_val},最大值{max_val},平均值{avg_val:.1f},中位数值{median_val}")
8.5 中文词频统计(project)
第1关读文件
# 请补充你的代码
file = '/data/bigfiles/二十大报告.txt'
with open(file, 'r', encoding='utf-8') as f:
txt = f.read()
n = int(input())
print(txt[:n])
第2关中文切分
import jieba
jieba.setLogLevel(jieba.logging.INFO)
file = '/data/bigfiles/二十大报告.txt'
with open(file, 'r', encoding='utf-8') as f:
txt = f.read()
n = int(input())
print(list(jieba.cut(txt))[:n]) # 精确模式
第3关统计词频
# 请补充你的代码
import jieba
jieba.setLogLevel(jieba.logging.INFO)
file = '/data/bigfiles/二十大报告.txt'
with open(file, 'r', encoding='utf-8') as f:
txt = f.read()
n = int(input())
dic = {}
for c in jieba.cut(txt):
dic[c] = dic.get(c, 0)+1 # 统计词频
dic = sorted(dic.items(), key=lambda x:x[1], reverse=True)
print(list(dic[:n]))
第4关去除单字词
# 请补充你的代码
import jieba
jieba.setLogLevel(jieba.logging.INFO)
file = '/data/bigfiles/二十大报告.txt'
with open(file, 'r', encoding='utf-8') as f:
txt = f.read()
n = int(input())
dic = {}
for c in jieba.cut(txt):
if len(c)>1:
dic[c] = dic.get(c, 0)+1
dic = sorted(dic.items(), key=lambda x:x[1], reverse=True)
print(list(dic[:n]))
第5关去除停用词
# 请补充你的代码
import jieba
jieba.setLogLevel(jieba.logging.INFO)
file = '/data/bigfiles/二十大报告.txt'
with open(file, 'r', encoding='utf-8') as f:
txt = f.read()
with open('/data/bigfiles/stopwordsshz.txt','r', encoding='utf-8') as f:
stop = f.read().split()
n = int(input())
dic = {}
for c in jieba.cut(txt):
if len(c)>1 and c not in stop: # 去除停用词
dic[c] = dic.get(c, 0)+1
dic = sorted(dic.items(), key=lambda x:x[1], reverse=True)
print(list(dic[:n]))