gpt4 book ai didi

java - Python代码到Java代码的转换

转载 作者:太空宇宙 更新时间:2023-11-04 11:53:21 27 4
gpt4 key购买 nike

我用 python 写了一些代码,效果非常好,我试图用 Java 实现它,但遇到了一些小问题。这是一个简单的 21 个问题,使用回溯法,获取用户输入的字符串,例如“1 9 10”

这是Python代码:

def twentyone(nums, stack = [], answer = set()):
for index, num in enumerate(nums):
new_stack = stack + [num]
total = sum(new_stack)
if total == 21:
answer.add(tuple(new_stack))
elif total < 21:
twentyone(nums[index + 1:], new_stack, answer)
return answer

user_input = input()
list_format = [int(x) for x in user_input.split()]
answer = twentyone(list_format)

if len(answer) == 0:
print("No combination of numbers add to 21")
for solution in answer:
print("The values ", end = "")
for number in solution:
print("{} ".format(number), end = "")
print("add up to 21")

这是我的 java 代码(到目前为止)

public class TwentyOne {

public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
String stringInput = userInput.nextLine();

ArrayList<Integer> allNum = new ArrayList<>();
for (String num : stringInput.split(" ")){
allNum.add(Integer.parseInt(num));
}

HashSet<ArrayList<Integer>> answer = twentyOne(allNum);

for (ArrayList<Integer> solution : answer){
System.out.print("The values ");
for (Integer num : solution){
System.out.print(num + " ");
}
System.out.println("Add up to 21");
}
}



private static HashSet twentyOne(ArrayList<Integer> user_input){

return new HashSet<ArrayList<Integer>>();
}
}

基本上,如果参数中没有变量初始化,我就无法绕过编写java递归问题。

def二十一(nums,stack = [],answer = set()):

所以我的问题是,如何在我将进行递归调用的方法中处理没有变量初始化的java回溯?

最佳答案

您将编写一个传递默认参数的包装方法。例如:

twentyone(List<Integer> nums) {
twentyoneRecursive(nums, new ArrayDeque<>(), new HashSet<>());
}

twentyoneRecursive(List<Integer> nums, Deque<Integer> stack, Set<List<Integer>> answer) {
...
twentyoneRecursive(...);
}

关于java - Python代码到Java代码的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41590108/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com