MST

星途 面试题库

面试题:Python数值列表简单统计计算之专家题

假设有多个数值列表(数量未知且每个列表大小也未知)存储在不同的文件中,文件格式为每行一个数值。编写一个Python程序,能够并行处理这些文件,计算所有数值的加权平均数(权重由每个数值在其所在列表中的位置决定,位置从1开始),并优化程序以提高在多核CPU环境下的执行效率,同时要处理文件读取过程中可能出现的各种异常情况。
24.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import concurrent.futures
import os


def calculate_weighted_sum(file_path):
    weighted_sum = 0
    total_weight = 0
    try:
        with open(file_path, 'r') as file:
            for position, line in enumerate(file, start=1):
                try:
                    value = float(line.strip())
                    weighted_sum += value * position
                    total_weight += position
                except ValueError:
                    pass
    except FileNotFoundError:
        pass
    except PermissionError:
        pass
    return weighted_sum, total_weight


def calculate_weighted_average(file_paths):
    total_weighted_sum = 0
    total_total_weight = 0
    with concurrent.futures.ProcessPoolExecutor() as executor:
        results = list(executor.map(calculate_weighted_sum, file_paths))
    for weighted_sum, total_weight in results:
        total_weighted_sum += weighted_sum
        total_total_weight += total_weight
    if total_total_weight == 0:
        return 0
    return total_weighted_sum / total_total_weight


if __name__ == '__main__':
    file_paths = []
    for root, dirs, files in os.walk('.'):
        for file in files:
            file_path = os.path.join(root, file)
            file_paths.append(file_path)
    average = calculate_weighted_average(file_paths)
    print(f"The weighted average is: {average}")
  1. calculate_weighted_sum函数
    • 该函数用于计算单个文件中数值的加权和以及总权重。
    • 它尝试打开文件,并逐行读取其中的数值。
    • 对于每一行,尝试将其转换为浮点数,如果转换成功,则计算加权值并累加到weighted_sum中,同时将位置权重累加到total_weight中。
    • 处理文件不存在(FileNotFoundError)和权限不足(PermissionError)等异常情况。
  2. calculate_weighted_average函数
    • 使用ProcessPoolExecutor创建进程池,并行处理所有文件路径。
    • 对每个文件调用calculate_weighted_sum函数,并收集结果。
    • 遍历结果,累加加权和和总权重,最后计算并返回加权平均数。
  3. 主程序部分
    • 使用os.walk获取当前目录及其子目录下的所有文件路径。
    • 调用calculate_weighted_average函数计算加权平均数并打印结果。
    • if __name__ == '__main__'语句用于确保在多进程环境下代码的正确执行,特别是在Windows系统上。