【头歌】Python 数学分析

python123题目——校验身份证号码并输出个人信息 校验身份证号码并输出个人信息 类型:流程控制。 阅读详情

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]))

【项目实战】使用Yolov8 + tesseract 实现身份证信息解析(OCR) + 输入可为图片或者pdf + 完整代码 + 整体方案 + 全网首发 使用Yolov8 + tesseract 实现身份证信息解析(OCR) + 输入可为图片或者pdf + 完整代码 + 整体方案 + 全网首发 阅读详情

相关推荐

基于OCR的身份证信息智能识别系统设计与实现

身份证识别技术作为智能身份认证的核心环节,广泛应用于金融开户、政务办理、出行安检等场景。其本质是通过图像处理与模式识别技术,自动提取身份证件中的姓名、号码、有效期等关键信息。随着深度学习的发展,传统OCR结合端到端神经网络模型显著提升了复杂环境下的识别准确率与鲁棒性,推动了无纸化、自助化服务的全面落地。该技术不仅要求高精度,还需兼顾安全性与合规性,为后续身份核验提供可靠数据支撑。

weixin_42234168的博客 1000

头歌Python作业——8.1 模拟生成身份信息及查验身份(project)

【代码】头歌Python作业——8.1 模拟生成身份信息及查验身份(project)

2201_75537843的博客 5877

NXP ChessDE的安装和激活

如果客户申请的是试用版,那么一份为期 30 天的 License 将会发送申请人的账号或邮箱中,客户使用该文件进行安装即可。② 将“VENDOR snpslmd /path/to/snpslmd”中的“/path/to/snpslmd”替换成 snpslmd.exe 实际存放路径(位于 SCL 安装目录下的 win32\bin 文件夹中,默认安装的情况下就是“VENDOR snpslmd C:\Synopsys\SCL\<version>\win32\bin\snpslmd.exe”)。

weixin_47351160的博客 2053

python实现模拟身份验证服务器综合系统设计

完成一个 Python 程序,实现密码存储和验证,用于模拟身份验证服务器,以便破解数据库的对手无法获得用户的明文密码。实现基本的注册和登录功能。测试样例如下: 该系统的源码如下: output 由输出可知,系统功能一切正常。受于文本篇幅原因,本文相关算法实现工程例如环境及相关库,无法展示出来,现已将资源上传,可自行点击下方链接下载。python实现模拟身份验证服务器综合系统工程文件......

timerring的博客 2万+

Android应用隐私合规自动化检测:Frida与Camille实战指南

在移动应用安全与隐私合规领域,动态代码插桩技术已成为核心检测手段。其原理是通过运行时注入,实时监控和修改应用行为,从而绕过传统静态分析的局限。这项技术的核心价值在于能够精准捕获应用在运行时的敏感数据调用与网络传输行为,为隐私合规审计、安全测试提供直接证据。在实际应用场景中,它尤其适用于自动化检测违规收集个人信息、追踪数据流向等任务。本文聚焦于利用Frida这一动态插桩框架,结合Camille隐私合规检测工具集,构建自动化监控环境。通过注入JavaScript代码,实现对Android敏感API(如获取设备标

weixin_34254464的博客 391

我用 AI 做了个开源地图工具:从 OpenStreetMap 一键获取全国 AOI/POI 数据

本文介绍了一款免费开源的OSM数据查询与可视化工具,旨在解决Overpass QL语法晦涩、数据获取门槛高的问题。工具支持面数据(AOI)、点数据(POI)及路网三种查询模式,内置30+常用模板实现一键检索。具备高德与OSM双底图切换、坐标自动转换功能,支持GeoJSON、SHP、CSV多格式导出,同时保留自定义查询能力。作为纯HTML单文件应用,可零成本部署至GitHub Pages在线使用。该工具有效降低了地理数据获取难度,是替代商业地图API、高效提取全球开源地理信息的实用利器。

weixin_45812624的博客 613

python实现模拟身份验证服务器综合系统设计_模拟生成身份信息及查验身份python

④ Python基础入门、爬虫、web开发、大数据分析方面的视频(适合小白学习)(img-WjlvZFEv-1712851877329)]① 2000多本Python电子书(主流和经典的书籍应该都有了)③ 项目源码(四五十个有趣且经典的练手项目及源码)⑤ Python学习路线图(告别不入流的学习)⑤ Python学习路线图(告别不入流的学习)② Python标准库资料(最全中文版)

m0_60607675的博客 1713

智能门禁:AI Agent的访客意图识别

随着人工智能技术的飞速发展,智能门禁系统已经成为现代安全管理的关键环节。本文深入探讨了AI Agent在访客意图识别中的应用,通过详细的分析和实例讲解,揭示了智能门禁系统的核心工作原理、算法实现及其在安全领域的重要作用。文章结构清晰,逻辑严谨,旨在为广大技术爱好者提供一次全面的技术盛宴。在当今社会,门禁系统已成为各类建筑和机构不可或缺的安全设施。随着信息安全意识的增强,传统门禁系统的局限性逐渐显现。例如,在访客管理方面,传统方法通常依赖于人工登记、身份验证等手段,不仅效率低下,而且容易出现漏洞。

AI架构师小马 717

chatgpt赋能python:用Python编写身份证校验程序

身份证是中华人民共和国居民的身份证明,也是常用的证件之一。身份证一般由18位数字组成,其中最后一位为校验码。校验码是用来校验身份证号码是否有效的。身份证号码的前17位是地区码、出生日期码和顺序码的组合。通过对这17位数字按照一定的算法进行处理,得到最后一位校验码。如果身份证号码最后一位与计算出的校验码不一致,那么该身份证就是无效的。本文由chatgpt生成,文章没有在chatgpt生成的基础上进行任何的修改。以上只是chatgpt能力的冰山一角。作为通用的Aigc大模型,只是展现它原本的实力。

tutan123321的博客 876

Challenge 6 - OSCP C

开放了161端口,直接snmpbulkwalk扫描得到账号密码试了那几个web端口,发现可以登录8083的vesta,但是需要用户名大写Jack接着登录之后里面可以创建计划任务,直接弄个反弹shell,一分钟回弹。得到shell后,运行linpeas.sh提供了几个可能的漏洞,挨个试一下。

羽的博客 4248

【面试系列】数据工程师高频面试题及详细解答

本文针对数据工程师岗位,提供了详尽的面试题库和解答,分为初级、中级和高级三个层次。初级面试题主要涉及基本的数据处理和ETL工具的使用,如SQL查询、数据清洗和基本的数据建模。中级面试题重点考察数据管道设计、数据库优化和大数据平台的应用。高级面试题则深入探讨高级数据处理技术、分布式系统架构和数据湖的实现。通过这些问题和解答,候选人可以全面了解数据工程师岗位所需的技能,帮助其更好地准备面试。常考知识点总结部分则系统归纳了数据工程师岗位的关键技能领域。

在路上的专栏 2377

【头歌-Python】8.3 政府工作报告数据提取(project)-第1~3关

附件中为2023年政府工作报告,本关要求将报告文件读取为一个字符串。 头歌-Educoder 8.3 政府工作报告数据提取(project) 前三关

谛凌的博客 9034

Docker 环境 Playwright MCP 部署全流程指南

Docker部署Playwright MCP全流程指南 本文详细介绍了使用Docker容器化部署Playwright MCP的完整流程,涵盖镜像拉取、容器启动、配置优化和问题排查。主要内容包括: 核心部署步骤:通过官方镜像快速搭建环境,支持自定义端口和数据持久化 关键配置要点:详解网络设置、持久化目录挂载和环境变量配置 服务验证方法:通过日志检查和服务连通性测试确保部署成功 客户端集成:提供VS Code等IDE的配置示例 常见问题解决:针对浏览器启动超时、跨域限制等问题给出解决方案 实战案例:演示自动化爬

勤奋的码农 1481

用python实现身份证号校验系统

使用Tkinter作为GUI模块以及python基础,开发一款身份证号码校验的系统。

ruwenbo的博客 4075

手把手教你学Simulink--复杂环境适应的四足机器人领域仿真建模实例:构建一个基于Simulink的四足机器人动态平衡保持仿真模型

通过上述步骤,你可以构建一个基本的基于Simulink的四足机器人动态平衡保持仿真模型。此模型不仅有助于理解四足机器人在复杂环境中的动态平衡控制原理,也为进一步优化提供了基础。随着技术的发展,还可以探索更多高级功能,如自适应步态调整、强化学习等,以提高机器人的智能性和适应性。

MHD0815的博客 245

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

2024年最全python基础(条件判断,input,循环,break,continue),面试提问的问题及答案

① 2000多本Python电子书(主流和经典的书籍应该都有了)② Python标准库资料(最全中文版)③ 项目源码(四五十个有趣且经典的练手项目及源码)④ Python基础入门、爬虫、web开发、大数据分析方面的视频(适合小白学习)⑤ Python学习路线图(告别不入流的学习)小案例name = input(“请输入姓名:”)height = float(input(“请输入身高(米):”))weight = float(input(“请输入体重(千克):”))tip = “”

2401_84140580的博客 1087

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

jsp input输入实时校验长度并提示_用Python写一个身份证号码校验系统

这是一个用Python开发的GUI实战项目:居民身份证信息校验系统一、总体介绍本项目使用Tkinter作为GUI模块,充分利用Python面向对象的思想,开发一款实现身份证号码校验的应用程序。具备解析用户输入的身份证号码中的地区信息、出生日期、以及身份证号码是否合法等功能。是一款练习Python面向对象思想、tkinter GUI模块的优质练手项目。项目演示以上,如果我们输入一个正确的身...

weixin_39589253的博客 746

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Python编程习题(8):查验身份证

一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下:首先对前17位数字加权求和,权重分配为:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};然后将计算的和对11取模得到值Z;最后按照以下关系对应Z值与校验码M现在给定一些身份证号码,请你验证校验码的有效性,并输出有问题的号码。

qq_68937706的博客 2197

【查验身份证】Python

【查验身份证】一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下:首先对前17位数字加权求和,权重分配为:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};然后将计算的和对11取模得到值Z;最后按照以下关系对应Z值与校验码M的值: Z:0 1 2 3 4 5 6 7 8 9 10 M:1 0 X 9 8 7 6 5 4 3 2 n ...

LiuLong0907的博客 6587

查验身份证(模拟)

查验身份证 一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下: 首先对前17位数字加权求和,权重分配为:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};然后将计算的和对11取模得到值Z;最后按照以下关系对应Z值与校验码M的值: Z:0 1 2 3 4 5 6 7 8 9 10 M:1 0 X 9 8 7 6 5 4 3 2 现在...

麦琪家的小麦 5893

用Python进行身份证号校验

在日常应用中,经常需要输入身份证号,因为号码较长容易录错,因此需要进行实时校验,以尽可能保证输入正确。以下以Python为例,浅聊身份证号码校验的方法。

hynet365的博客 8761

基于PaddleOCR+NLP实现证件文书识别(以身份证为例)

三方OCR服务价格普遍不便宜,随着公司业务量的增长,这部分成本逐渐变得难以忽视,因此内部评估后决定自行实现。

我的git仓库:https://github.com/daimengdewo?tab=repositories 3614

实战案例!用1行Python代码识别身份证信息,准确率超过99%,YYDS

录入身份证信息是一件繁琐的工作,如果可以自动识别并且录入系统,那可真是太好了。今天我们就来学习一下,如何自动识别身份证信息并且录入系统~

mate1357的博客 3887

PYTHON第二次实验

PYTHON第二次实验 实验2.1 批量生成姓名、家庭住址、电子邮箱等随机信息 一、实验目的 熟练运用标准库random中的函数 了解标准库string中的字符串常量 了解汉字编码格式 熟练掌握文本文件的操作方法 在文件操作时养成使用上下文管理语句with的习惯 二、实验内容 ​ 编写程序,生成200个人的模拟信息,包括姓名、性别、年龄、电话号码、家庭住址、电子邮箱地址,把生成的信息写入文本文件,每行存放一个人的信息,最后再读取生成的文本文件并输出其中的信息。 三、实验步骤 1.随机生成姓名 有关ch

qq_45831209的博客 6724

人生重开模拟器~Python实现

【代码】人生重开模拟器~Python实现。

lzf的博客 834

【Python习题】校验身份证号码并输出个人信息

校验身份证号码并输出个人信息

m0_61181620的博客 9454
上一篇: 8.3 政府工作报告数据提取(project)
下一篇: 【头歌 湖南工业大学】程序设计基础Python-编程作业
一只小邢
博客等级 码龄5年 9粉丝 13原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值