Python程序:计算两种货币的兑换汇率


假设我们有三个数组:curr_a、curr_b和conv_rate。前两个数组包含一些货币名称,conv_rate数组包含curr_a[i]到curr_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为True且i <= temp的大小,执行循环:
    • p := False
    • 对于curr_a中的每个x,curr_b中的每个y和conv_rate中的每个z,执行循环:
      • 如果temp[x] * z > temp[y] 且 temp[y]不为零,则:
        • temp[y] := temp[x] * z
        • p := True
      • i := i + 1
  • 如果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

更新于:2021年10月16日

浏览量:207

开启你的职业生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.