1

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!

3
  • 1
    Removing the Java tag assuming you don't want the answer in Java. Commented Jul 30, 2016 at 9:44
  • Your parentheses are different. The call to addCommas should end after number[:len(number) - 3] but it doesn't. return addCommas(number[:len(number) - 3]) + ',' + number[len(number) - 3:] Commented Jul 30, 2016 at 9:47
  • I feel very dumb right now, thanks a lot for your time! Commented Jul 30, 2016 at 9:53

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The difference is in the last line

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

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

are not same. If you observe in java you are calling addCommas and then appending comma and a string. Whereas in python you are only calling addCommas function.This will lead to infinite loop. Just do it same as in java.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.