Jack Ryan Jack Ryan - 1 year ago 65
Java Question

Python vs Java Loop

I am working through some problems on HackerRank, and I thought I would try implementing the same solution in Python that I had already solved correctly in Java. Although my code almost exactly mirrors my previous Python solution, I am getting an out of bounds exception in the

if input_str[i-1] == input_str[i]
line. Is there different behavior in a Python loop that might be causing this discrepancy? The test cases are the same across both.

public class Solution {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
public static void solve(String str) {
String s = new String(str);
for (int i=1; i < s.length(); i++) {
if (s.charAt(i-1) == s.charAt(i)) {
s = s.substring(0, i-1) + s.substring(i+1, s.length());
i = 0;
if (s.length() == 0) {
System.out.println("Empty String");

And this is the code for the same problem, but using Python 2.7.

input_str = raw_input()
for i in xrange(1, len(input_str)):
if input_str[i-1] == input_str[i]:
input_str = input_str[0:i-1] + input_str[i+1:len(input_str)]
i = 0
if len(input_str) == 0:
print "Empty String"

print input_str

Answer Source

In the Java loop, s.length() is recalculated every iteration. In Python, len(input_str) is only calculated once and does not reflect the correct length after you've modified input_str in the if block.

Similarly, assigning i = 0 does not work the way you want it to. i will take on the next value in the xrange, ignoring your attempted reset of its value.

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