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();
solve(input);
}
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");
return;
}
}
System.out.println(s);
}
}
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"
break
print input_str