I do like the way I can treat lists in Python. It does any recursion solution to look easy and clean. For instance the typical problem of getting all the permutations of elements in a list, in Python looks like:
def permutation_recursion(numbers,sol):
if not numbers:
print "this is a permutation", sol
for i in range(len(numbers)):
permutation_recursion(numbers[:i] + numbers[i+1:], sol + [numbers[i]])
def get_permutations(numbers):
permutation_recursion(numbers,list())
if __name__ == "__main__":
get_permutations([1,2,3])
I do like the way I can simple get new instances of modified lists by doing things like
numbers[:i] + numbers[i+1:]
or sol + [numbers[i]]
If I try to code exactly the same in Java, it looks like:
import java.util.ArrayList;
import java.util.Arrays;
class rec {
static void permutation_recursion(ArrayList<Integer> numbers, ArrayList<Integer> sol) {
if (numbers.size() == 0)
System.out.println("permutation="+Arrays.toString(sol.toArray()));
for(int i=0;i<numbers.size();i++) {
int n = numbers.get(i);
ArrayList<Integer> remaining = new ArrayList<Integer>(numbers);
remaining.remove(i);
ArrayList<Integer> sol_rec = new ArrayList<Integer>(sol);
sol_rec.add(n);
permutation_recursion(remaining,sol_rec);
}
}
static void get_permutation(ArrayList<Integer> numbers) {
permutation_recursion(numbers,new ArrayList<Integer>());
}
public static void main(String args[]) {
Integer[] numbers = {1,2,3};
get_permutation(new ArrayList<Integer>(Arrays.asList(numbers)));
}
}
To create the same recursion I need to do :
ArrayList<Integer> remaining = new ArrayList<Integer>(numbers);
remaining.remove(i);
ArrayList<Integer> sol_rec = new ArrayList<Integer>(sol);
sol_rec.add(n);
Which is quite ugly and it gets worse for more complex solutions. Like in this example
So my question is ... are there any buil-in operators or helper functions in the Java API that would make this solution more "Pythonic" ?
No.
But this is why Martin Odersky created Scala. He's even said that one of his goals for Scala is that it be the Python of the Java world. Scala compiles to Java bytecode and easily interops with Java compiled classes.
If that's not an option, you could take a look at the Commons Collection Library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With