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

相关推荐
牛客企业服务几秒前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘
胡斌附体12 分钟前
linux测试端口是否可被外部访问
linux·运维·服务器·python·测试·端口测试·临时服务器
likeGhee1 小时前
python缓存装饰器实现方案
开发语言·python·缓存
项目題供诗1 小时前
黑马python(二十五)
开发语言·python
读书点滴1 小时前
笨方法学python -练习14
java·前端·python
笑衬人心。1 小时前
Ubuntu 22.04 修改默认 Python 版本为 Python3 笔记
笔记·python·ubuntu
蛋仔聊测试2 小时前
Playwright 中 Page 对象的常用方法详解
python
前端付豪2 小时前
17、自动化才是正义:用 Python 接管你的日常琐事
后端·python
jioulongzi2 小时前
记录一次莫名奇妙的跨域502(badgateway)错误
开发语言·python
破无差2 小时前
python实现简单的地图绘制与标记20250705
python