用 Python 编写程序来找出两种货币的兑换率
pythonserver side programmingprogramming更新于 2026/1/11 15:08:17
假设我们有三个数组:curr_a、curr_b 和 conv_rate。第一个数组包含一些货币名称,第二个数组也包含一些货币名称,数组 conv_rate 包含 curr_a[i] 项到 cuur_b[i] 的兑换率。conv_rate[i] 项是 curr_a[i] 和 curr_b[i] 之间的兑换率。现在,我们给出了两种货币 src 和 dest。我们必须找出从 src 到 dest 的兑换率。我们将该值作为输出返回,如果不可能,则返回 0。
因此,如果输入为 src = "INR", dest = "JPY", curr_a = ["INR", "GBP", "EUR"], curr_b = ["GBP", "EUR", "JPY"], conv_rate = [0.009, 1.17, 129.67],则输出将为 1.3654250999999997
为了解决这个问题,我们将遵循以下步骤 −
- temp := 一个包含 0 作为默认值的新映射
- temp[src] := 1
- i := 0
- p := True
- 当 p 和 i <= temp 的大小时,执行
- p := False
- 对于 curr_a 中的每个 x、curr_b 中的 y 和 conv_rate 中的每个 z,执行
- 如果 temp[x] * z > temp[y] 非零,则
- temp[y] := temp[x] * z
- p := True
- i := i + 1
- 如果 temp[x] * z > temp[y] 非零,则
- 如果 i <= temp 的大小,则
- 返回 temp[dest]
- 否则,
- 返回 -1
示例
让我们看看下面的实现以便更好地理解 −
from collections import defaultdict
def solve(src, dest, curr_a, curr_b, conv_rate):
temp = defaultdict(int)
temp[src] = 1
i = 0
p = True
while p and i <= len(temp):
p = False
for x, y, z in zip(curr_a, curr_b, conv_rate):
if temp[x] * z > temp[y]:
temp[y] = temp[x] * z
p = True
i += 1
return temp[dest] if i <= len(temp) else -1
print(solve("INR", "JPY", ["INR", "GBP", "EUR"], ["GBP", "EUR", "JPY"], [0.009, 1.17, 129.67]))
输入
"INR", "JPY", ["INR", "GBP", "EUR"], ["GBP", "EUR", "JPY"], [0.009, 1.17, 129.67]
输出
1.3654251
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

