如何将这种递归Java方法转换为迭代方法?(CodeJam挑战赛)
我正试图将这一点适应Python的代码阻塞问题。不幸的是,它需要太深的递归才能在Python中正常工作(除非递归限制和堆栈大小都显著增加)。所以我尝试将这个递归转换为迭代:如何将这种递归Java方法转换为迭代方法?(CodeJam挑战赛),java,python,python-3.x,recursion,iteration,Java,Python,Python 3.x,Recursion,Iteration,我正试图将这一点适应Python的代码阻塞问题。不幸的是,它需要太深的递归才能在Python中正常工作(除非递归限制和堆栈大小都显著增加)。所以我尝试将这个递归转换为迭代: /** * Attempt to recursively free a die by selecting a different die for the same value. * @return true if the die has been freed, false if no other die can be f
/**
* Attempt to recursively free a die by selecting a different die for the same value.
* @return true if the die has been freed, false if no other die can be found.
*/
boolean freeByShuffling(Die die) {
assert die.valueUsing != null;
// First check if we can just use another dice for the previous value
for (Die otherDie : die.valueUsing.dice) {
if (otherDie.valueUsing == null) {
otherDie.valueUsing = die.valueUsing;
die.valueUsing = null;
return true;
}
}
// Nope, we must free a die recursively
diceVisitedWhileShuffling.add(die);
for (Die otherDie : die.valueUsing.dice) {
if (diceVisitedWhileShuffling.contains(otherDie)) continue;
if (freeByShuffling(otherDie)) {
otherDie.valueUsing = die.valueUsing;
die.valueUsing = null;
return true;
}
}
return false;
}
这是我的Python代码,虽然它解决了大多数测试用例,但并不十分有效:
def free_by_shuffling(self, die):
assert die.current_value is not None
stack = [(None, die)]
found = False
while stack:
this_die, other_die = stack.pop()
self.visited.add(other_die)
if found:
other_die.current_value = this_die.current_value
this_die.current_value = None
continue
for next_die in other_die.current_value.dice:
if next_die in self.visited:
continue
if next_die.current_value is None:
found = True
stack.append((other_die, next_die))
break
else:
for next_die in other_die.current_value.dice:
if next_die in self.visited:
continue
stack.append((other_die, next_die))
return found
如何将原始方法转换为使用迭代而不是递归?此Python实现适用于“小”和“大”输入文件:
def free_by_shuffling(self, die):
assert die.current_value is not None
stack = [die]
found = False
while stack:
this_die = stack.pop()
if found:
if stack:
this_die.current_value = stack[-1].current_value
stack[-1].current_value = None
continue
for other_die in this_die.current_value.dice:
if other_die.current_value is None:
stack.extend((this_die, other_die))
found = True
break
else:
self.visited.add(this_die)
for other_die in this_die.current_value.dice:
if other_die not in self.visited:
stack.extend((this_die, other_die))
break
else:
if stack:
for other_die in stack[-1].current_value.dice:
if other_die not in self.visited:
stack.append(other_die)
break
return found
欢迎您提出任何意见和建议。您的解决方案“不太有效”的原因是什么?@Chris:少数测试用例的答案与迭代函数有误(通过
1
或2
关闭),当使用递归的时候,所有的答案都是正确的。我在你的解决方案中改变了一些东西,现在只有4个测试用例是不正确的。我会继续试着看我是否能得到它。我被这个问题上的投票弄糊涂了。它是否明显违反了“寻求调试帮助的问题(“此代码为什么不工作?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码”?“不太管用”和“少数测试用例的错误率为1或2”(特别是没有细节)都不是明确的问题陈述。OP在这里已经有很长时间了;他们肯定知道这不是一个好问题吗?@Chris:再读一遍标题。我不寻求调试帮助。