用Python找出两种货币的兑换率的程序
假设我们有三个数组;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
示例
让我们看看以下实现以获得更好的理解-
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