399. Evaluate Division

本文介绍了一种使用图算法解决变量间复杂关系计算的方法。通过构建图结构,将变量作为节点,变量间的数学关系作为边的权重,利用深度优先搜索(DFS)算法寻找两变量间的路径并计算其关系值。此方法适用于处理多个变量间的关系,如在给定一些变量比例关系后,求解未知变量的比例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.

Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].

The input is: vector<pair<string, string>> equations, vector& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector.

According to the example above:

equations = [ [“a”, “b”], [“b”, “c”] ],
values = [2.0, 3.0],
queries = [ [“a”, “c”], [“b”, “a”], [“a”, “e”], [“a”, “a”], [“x”, “x”] ].
The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.

Problem URL


Solution

给一组数相除的结果,返回一组query的结果,如果无法计算,返回-1.0.

We use two hash maps to contruct a graph according to equations and values. Then variables in equations are nodes in a graph, values are the weight from node a to node b. Pairs map stores the edges of a node, and valuesPair stores the weight information. First using a for loop to iteratively travel equations and values. Adding edges and weights to pairs and values pair.

Then iteratively access queries, using dfs to find a path from query[0] to query[1]. If does not have this path, return 0.0, and then update -1.0 to res.

For the dfs function, we use a hash set to store nodes we have visited. If a circle is formatted or pairs does not contain start, return 0.0. If found end, return current value; For dfs, we get the edge info and weight info of start node, and iteratively travels the edges using dfs and updated node and values. Remember to remove start in set for upper level use.

Code
class Solution {
    private HashMap<String, ArrayList<String>> pairs;
    private HashMap<String, ArrayList<Double>> valuesPair;
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        pairs = new HashMap<>();
        valuesPair = new HashMap<>();
        for (int i = 0; i < equations.length; i++){
            String[] equation = equations[i];
            if (!pairs.containsKey(equation[0])){
                pairs.put(equation[0], new ArrayList<String>());
                valuesPair.put(equation[0], new ArrayList<Double>());
            }
            if (!pairs.containsKey(equation[1])){
                pairs.put(equation[1], new ArrayList<String>());
                valuesPair.put(equation[1], new ArrayList<Double>());
            }
            pairs.get(equation[0]).add(equation[1]);
            pairs.get(equation[1]).add(equation[0]);
            valuesPair.get(equation[0]).add(values[i]);
            valuesPair.get(equation[1]).add(1 / values[i]);
        }
        
        double[] res = new double[queries.length];
        for (int i = 0; i < queries.length; i++){
            String[] query = queries[i];
            res[i] = dfs(query[0], query[1], new HashSet<String>(), 1.0);
            if (res[i] == 0.0){
                res[i] = -1.0;
            }
        }
        return res;
    }
    
    private double dfs(String start, String end, HashSet<String>set, double value){
        if (set.contains(start)){
            return 0.0;
        }
        if (!pairs.containsKey(start)){
            return 0.0;
        }
        if (start.equals(end)){
            return value;
        }
        set.add(start);
        
        ArrayList<String> strList = pairs.get(start);
        ArrayList<Double> valueList = valuesPair.get(start);
        double temp = 0.0;
        for (int i = 0; i < strList.size(); i++){
            temp = dfs(strList.get(i), end, set, value * valueList.get(i));
            if (temp != 0.0) {
                break;
            }
        }
        set.remove(start);
        return temp;
    }
}

Time Complexity: O()
Space Complexity: O()


Review
<think>好的,用户让我介绍一下这段Python代码中的`from __future__ import division`,以及可能涉及的其他部分。首先,我需要确定用户对Python的了解程度,但根据他们的问题,可能有一定的编程基础,但可能不熟悉某些特定的导入或语法。 首先,`from __future__ import division`这个语句的作用是什么?我记得`__future__`模块用于在旧版本的Python中启用新版本的功能。这里导入的是division,所以应该是改变除法运算的行为。在Python 2中,除法运算符`/`在整数相除时会进行地板除,比如3/2得到1。而导入这个特性后,3/2会变成1.5,和Python 3的行为一致。而`//`则用于地板除。这点需要解释清楚,尤其是用户可能从Python 3转来,或者在使用旧代码时遇到这个问题。 接下来,用户提供的代码片段看起来像是一个深度学习项目的一部分,比如对象检测。因为导入了models、utils中的各种模块,还有evaluate函数。可能用户是在处理像YOLO这样的模型,因为类似的结构常见于这类项目。不过用户的问题主要集中在`__future__`导入,所以这部分可能不需要深入,除非用户有其他疑问。 然后,其他导入部分,比如`from models import *`,这里可能导入了所有的模型类,但通常不建议使用通配符导入,因为可能导致命名冲突。不过这在某些项目中常见,特别是快速开发时。同样,`from utils.utils import *`可能导入了一些工具函数,比如数据加载、配置解析等。`from test import evaluate`可能导入了测试用的评估函数。 用户可能想知道这些导入的作用,但他们的主要问题还是关于`__future__`语句。需要确保解释清楚为什么需要这个导入,特别是在Python 2和3的兼容性方面。同时,用户可能在使用或维护旧代码时遇到这种情况,所以需要说明兼容性问题和迁移注意事项。 另外,代码中还有`import warnings`,可能用于控制警告信息的显示,比如忽略某些警告,但用户并没有提到这个,可能暂时不需要深入。不过可以提到如果有未使用的警告或其他问题,可能需要处理。 总结回答的结构:先解释`from __future__ import division`的作用,然后简要提及其他导入的可能用途,最后给出使用场景和注意事项。确保语言简洁,结构清晰,分点说明,帮助用户逐步理解。</think>关于你提供的代码片段中的`from __future__ import division`及相关内容,以下是分步解析: --- ### 一、`from __future__ import division` 的作用 1. **Python 2/3 兼容性** 这是Python 2中引入未来版本(Python 3)特性的语法。当你在Python 2脚本中使用这一行时,会强制代码中的除法行为与Python 3一致。 2. **除法行为的改变** - **Python 2默认行为**:`/` 表示**整数除法**(地板除),例如 `3 / 2` 结果为 `1`。 - **导入后行为**:`/` 表示**浮点除法**,例如 `3 / 2` 结果为 `1.5`;若需整数除法,需显式使用 `//`。 3. **何时需要它** 当你的代码需要同时在Python 2和Python 3中运行时,此导入可避免因除法行为不同导致的错误。 --- ### 二、其他导入语句解析 #### 1. 项目相关模块 ```python from models import * from utils.logger import * from utils.utils import * from utils.datasets import * from utils.parse_config import * from test import evaluate ``` - **`models`**:通常包含神经网络模型的定义(如YOLO等目标检测模型)。 - **`utils` 子模块**: - `logger`:日志记录工具(如训练日志、性能指标记录)。 - `utils`:通用工具函数(如数据加载、张量操作)。 - `datasets`:数据集加载与预处理逻辑。 - `parse_config`:解析配置文件(如模型超参数、路径配置)。 - **`test import evaluate`**:导入评估函数,用于模型性能测试(如计算mAP、准确率)。 #### 2. `import warnings` - **用途**:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值