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

開啟你的職業生涯

完成課程,獲得認證

開始學習
廣告