我想将一个 Python 程序(解决某个基本的组合问题)翻译成 Javascript。目标是评估my_function(200, [1,2,5,10,20,50,100,200]),结果是Python程序返回正确答案(~70k),但是我的尝试的 Javascript 翻译返回错误答案(~60k)。
函数 my_function 是递归定义的,特别是第二个输入,一个列表,在递归步骤中被 chop (参见代码的倒数第二行)。我可能在 JS 版本中处理得不好。
Python 函数:
import math
coin_sizes = [1,2,5,10,20,50,100,200]
def my_function(amount, coins_list):
if amount == 0:
return 1
elif len(coins_list) == 0:
return 0
elif len(coins_list) == 1:
return 1
else:
top_coin = coins_list[-1]
d = math.floor(amount/top_coin)
total = 0
for i in range(0,d+1):
total += my_function(amount - i*top_coin, coins_list[:-1])
return total
Javascript 函数:
var coin_sizes = [1,2,5,10,20,50,100,200];
var sublist = function(mylist) {
var new_list = Array(mylist.length-1);
for (var i = 0; i < mylist.length-1; i++){
new_list[i] = mylist[i];
}
return new_list
};
var my_function = function(amount, coins_list) {
if (amount == 0) return 1;
else if (coins_list.length == 0) return 0;
else if (coins_list.length == 1) return 1;
else {
var top_coin = coins_list[(coins_list.length-1)];
d = Math.floor(amount/top_coin);
var total = 0;
for (var i = 0; i < d+1; i++) {
total += my_function(amount - i*top_coin, sublist(coins_list));
};
return total;
};
};
我尝试用 Java 编写一个类似的程序,但出现了太多堆栈溢出错误。
问题:发生了什么事?为什么我会得到错误的答案,有没有更好的方法将这个 Python 程序翻译成 Javascript?
注意:原来的组合问题可以动态地/不递归地解决,然后我将它翻译成 Javascript 就没有问题了。我想学习如何编写类似于上面的 Python 函数的东西。
最佳答案
你错过了声明 d
。
顺便说一句,您可以使用 exit early paradigm if ... return ...
并在没有 else
的情况下继续,对于最后一个 block ,您需要声明所有变量,因为如果不是,则变量是全局的,并且值会随着递归调用而变化。
另一个提示,在 block 语句 { ... }
之后,例如 for
或 else
,您不需要分号。
最后,您可以使用 Array#slice
用于获取从开始到结束的副本 - 1 通过使用 -1
作为 to 参数(第二个)。
var coin_sizes = [1, 2, 5, 10, 20, 50, 100, 200],
sublist = function(mylist) {
return mylist.slice(0, -1);
},
my_function = function(amount, coins_list) {
if (amount == 0) return 1;
if (coins_list.length == 0) return 0;
if (coins_list.length == 1) return 1;
var top_coin = coins_list[(coins_list.length - 1)],
d = Math.floor(amount / top_coin),
total = 0;
for (var i = 0; i < d + 1; i++) {
total += my_function(amount - i * top_coin, sublist(coins_list));
}
return total;
};
console.log(my_function(200, [1, 2, 5, 10, 20, 50, 100, 200]));
关于javascript - 递归 Python 函数转换为 Javascript 不起作用,数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52793745/