677. Map Sum Pairs

Implement a MapSum class with insert, and sum methods.

For the method insert, you’ll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.

For the method sum, you’ll be given a string representing the prefix, and you need to return the sum of all the pairs’ value whose key starts with the prefix.

Example 1:

Input: insert("apple", 3), Output: Null
Input: sum("ap"), Output: 3
Input: insert("app", 2), Output: Null
Input: sum("ap"), Output: 5

思路:
For each key in the map, if that key starts with the given prefix, then add it to the answer.

class MapSum {
    HashMap<String, Integer> map;
    /** Initialize your data structure here. */
    public MapSum() {
        map = new HashMap<>();
    }

    public void insert(String key, int val) {
        map.put(key, val);
    }

    public int sum(String prefix) {
        int ans = 0;
        for (String key: map.keySet()) {
            if (key.startsWith(prefix)) {
                ans += map.get(key);
            }
        }
        return ans;
    }
}

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum obj = new MapSum();
 * obj.insert(key,val);
 * int param_2 = obj.sum(prefix);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个问题可能是因为在计算 E(G) 时,某些节点之间的最短路径长度为 0。这可能是因为在 csv 文件中存在自环,即源节点和目标节点是同一个节点,或者两个节点之间没有边连接。 可以通过在计算 E(G) 之前先检查图中是否有自环或孤立节点来解决这个问题。如果出现这些情况,可以通过删除自环或孤立节点来处理。 以下是修改后的代码,包括检查自环和孤立节点的代码: ```python import pandas as pd import networkx as nx import os from multiprocessing import Pool def process_csv(csv_path): df = pd.read_csv(csv_path, header=None, names=['source', 'target', 'weight'], delim_whitespace=True) # Remove self-loops and isolated nodes df = df[df['source'] != df['target']] nodes = set(df['source']) | set(df['target']) G = nx.Graph() G.add_nodes_from(nodes) for index, row in df.iterrows(): G.add_edge(row['source'], row['target'], weight=row['weight']) dist_matrix = dict(nx.all_pairs_dijkstra_path_length(G)) with open(os.path.splitext(csv_path)[0] + '.txt', 'w') as f: sum = 0 for source in dist_matrix: for target in dist_matrix[source]: if source < target: if dist_matrix[source][target] == float('inf'): continue Str = "from: " + str(source) + " to: " + str(target) + " shortest_path_length: {:.2f}".format(dist_matrix[source][target]) f.write(Str + '\n') sum += 1 / dist_matrix[source][target] N = G.number_of_nodes() if N <= 1: ret = 'E(G)=0' else: ret = 'E(G)={:.4f}'.format(sum / (N * (N - 1))) print(ret) f.write(ret + '\n') if __name__ == '__main__': folder_path = r'D:\2012POI\大连市2012_网络' csv_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.csv')] pool = Pool() pool.map(process_csv, csv_files) pool.close() pool.join() ``` 这个代码首先检查了 csv 文件中是否有自环,如果有自环就删除。然后检查了是否有孤立节点,如果有孤立节点,就在图中添加这些节点,并且不会增加 E(G)。最后,在计算 E(G) 时,跳过了最短路径长度为无穷大的节点对。 另外,修改后的代码还增加了对节点数量少于 2 的情况的处理。如果只有一个节点,则没有边,E(G) 等于 0。如果有两个节点,则只有一条边,E(G) 等于这条边的权重。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值