BuggyLemon BuggyLemon - 1 year ago 52
Python Question

Code works in Java but not Python?

This code seems to work in Java, but when I convert it to Python, it exceeds the maximum recursion depth and exits.. Not sure what the difference is. They look like they function identically to me.

Java version:

public String addCommas(String number)
{
if(number.length < 4
{
return number;
}
return addCommas(number.subString(0, number.length - 3)) + "," + number.subString(number.length - 3, number.length);
}


Python version:

def addCommas(number):
number = str(number)
if len(number) < 4:
return number
else:
return addCommas(number[:len(number) - 3] + ',' + number[len(number) - 3:])


Thanks in advance for any help!

Answer Source

The difference is in the last line.

 return addCommas(number.subString(0, number.length - 3)) + "," + number.subString(number.length - 3, number.length);

This calls addCommas on the first substring only (which reduces the length of the string parameter for the next call by 3) and then appends a comma and the last three digits to its result.

 return addCommas(number[:len(number) - 3] + ',' + number[len(number) - 3:])

This on the other hand first adds a comma and calls addCommas on the whole new string (which is even longer than the original, resulting in the infinite recursion loop).

 return addCommas(number[:len(number) - 3]) + ',' + number[len(number) - 3:]

This would work as it only calls addCommas on the first substring and adds the commas to the result of addCommas, the same way the Java code does it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download