I've come across a question when I was looking at a bunch of algorithms for fun. The algorithm that I solved (in Java) asks me to list all the partitions of an integer. So the partitions of 4 should receive the following printed output:
4 , 3+1, 2+2, 2+1+1, 1+1+1+1
This is my code in Java:
public static void partition(int n) {
partition(n, n, "");
}
public static void partition(int n, int max, String prefix) {
if (n == 0) {
StdOut.println(prefix);
return;
}
for (int i = Math.min(max, n); i >= 1; i--) {
partition(n-i, i, prefix + " " + i);
}
}
However, when I tried to convert my Java code to Python, I get the "recursion depth exceed" error. Here it is:
def partition_rec(N):
def part(N,maximum = N, prefix = ""):
if(N==0):
print(prefix)
return
for i in range(N-1):
part(N-i,i,prefix + " " + str(i))
return part(N)
Could someone help me out? Thanks!