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

相关推荐
wyiyiyi7 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
mit6.8247 小时前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
没有bug.的程序员7 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋8 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
AntBlack8 小时前
不当韭菜V1.1 :增强能力 ,辅助构建自己的交易规则
后端·python·pyqt
杜子不疼.10 小时前
《Python学习之字典(一):基础操作与核心用法》
开发语言·python·学习
myzzb11 小时前
基于uiautomation的自动化流程RPA开源开发演示
运维·python·学习·算法·自动化·rpa
TLuoQiu11 小时前
小电视视频内容获取GUI工具
爬虫·python
我叫黑大帅11 小时前
【CustomTkinter】 python可以写前端?😆
后端·python
胡耀超11 小时前
DataOceanAI Dolphin(ffmpeg音频转化教程) 多语言(中国方言)语音识别系统部署与应用指南
python·深度学习·ffmpeg·音视频·语音识别·多模态·asr