2023华为od机试C卷【API集群负载统计】Python实现


思路

统计第二层级上computing出现的次数的时候,只需要for循环寻找computing是否在字典的键中。

如果找到,计数的时候是加上computing对应的值

python 复制代码
def main():
    import collections
    length_char = int(input())
    node_info = {}
    for i in range(length_char):
        char_list = [s for s in input().split('/') if s]
        char_dict = collections.Counter(char_list)
        node_info[i+1] = char_dict
    node = int(input())
    target_str = input()
    target_count = 0
    for i in range(node):
        temp = node_info[i+1]
        if target_str in temp:
            target_count += temp[target_str]
    print(target_count)
if __name__ == "__main__":
    main()

代码功能概述

这个程序的目的是分析一组输入的字符并计算某个目标字符在特定节点中出现的次数。

逐步解析代码

  1. 导入库:

    python 复制代码
    import collections

    这行代码导入了 collections 模块,主要用来使用 Counter 类,它可以用来计数对象出现的次数。

  2. 主函数定义:

    python 复制代码
    def main():

    这是主函数定义,程序的执行从这里开始。

  3. 输入字符数量:

    python 复制代码
    length_char = int(input())

    这一行从用户输入获取一个整数,表示接下来将输入的字符组的数量(节点的数量)。

  4. 初始化字典:

    python 复制代码
    node_info = {}

    创建一个空字典 node_info,用于存储每个节点的字符计数信息。

  5. 循环输入并处理字符:

    python 复制代码
    for i in range(length_char):
        char_list = [s for s in input().split('/') if s]
        char_dict = collections.Counter(char_list)
        node_info[i+1] = char_dict
    • 在这个循环中,根据 length_char 的数量,逐行读取输入。
    • 使用 input().split('/') 方法把输入的字符串按斜杠(/)分割成字符列表。
    • 过滤掉空字符串。
    • 使用 collections.Counter 创建一个字典 char_dict,该字典记录每个字符出现的次数。
    • node_info[i+1] = char_dict 把每个节点的字符计数存入 node_info 字典,键是节点编号(从1开始)。
  6. 输入节点数量:

    python 复制代码
    node = int(input())

    获取用户输入的一个整数,表示需要检查的节点数量。

  7. 输入目标字符:

    python 复制代码
    target_str = input()

    获取用户输入的一个字符串,即需要计算出现次数的目标字符。

  8. 统计目标字符的次数:

    python 复制代码
    target_count = 0
    for i in range(node):
        temp = node_info[i+1]
        if target_str in temp:
            target_count += temp[target_str]
    • 初始化计数器 target_count 为 0。
    • 遍历每个节点,检查 node_info 中相应节点所存储的字符计数(temp)。
    • 如果 target_str 在当前节点的计数字典中,则将 target_count 加 temp[target_str]。
  9. 输出结果:

    python 复制代码
    print(target_count)

    打印最终统计的目标字符出现的节点数量。

  10. 程序入口:

    python 复制代码
    if __name__ == "__main__":
        main()

    这一行确保只有在直接运行此文件时才执行主函数 main

相关推荐
Empty_7772 小时前
编程之python基础
开发语言·python
哲Zheᗜe༘5 小时前
了解学习Python编程之python基础
开发语言·python·学习
麦麦大数据5 小时前
F024 RNN+Vue+Flask电影推荐可视化系统 python flask mysql 深度学习 echarts
python·rnn·深度学习·vue·echarts·电影推荐
Roc-xb6 小时前
ModuleNotFoundError: No module named ‘conda_token‘
开发语言·python·conda
weixin_525936336 小时前
部分Spark SQL编程要点
大数据·python·sql·spark
Xyz996_6 小时前
python编程基础知识
python
人工干智能7 小时前
Python 开发中:`.ipynb`(Jupyter Notebook 文件)和 `.py`(Python 脚本文件)
开发语言·python·jupyter
woshihonghonga7 小时前
Jupyter Notebook单元格输出换行问题解决
ide·python·jupyter
~~李木子~~7 小时前
Jupyter Notebook(ipynb)转 Python(py)文件
python·jupyter
ERROR_LESS7 小时前
【ADS-1】【python基础-1】jupyter notebook环境极简搭建
python·jupyter