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

相关推荐
橡晟4 小时前
深度学习入门:让神经网络变得“深不可测“⚡(二)
人工智能·python·深度学习·机器学习·计算机视觉
墨尘游子4 小时前
神经网络的层与块
人工智能·python·深度学习·机器学习
倔强青铜34 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
企鹅与蟒蛇5 小时前
Ubuntu-25.04 Wayland桌面环境安装Anaconda3之后无法启动anaconda-navigator问题解决
linux·运维·python·ubuntu·anaconda
autobaba5 小时前
编写bat文件自动打开chrome浏览器,并通过selenium抓取浏览器操作chrome
chrome·python·selenium·rpa
Rvelamen6 小时前
LLM-SECURITY-PROMPTS大模型提示词攻击测评基准
人工智能·python·安全
【本人】6 小时前
Django基础(一)———创建与启动
后端·python·django
SHIPKING3937 小时前
【python】基于pygame实现动态粒子爱心
开发语言·python·pygame
kk_stoper9 小时前
如何通过API查询实时能源期货价格
java·开发语言·javascript·数据结构·python·能源
java1234_小锋9 小时前
【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 架构搭建
python·自然语言处理·flask