Python vs Java Loop -


i working through problems on hackerrank, , thought try implementing same solution in python had solved correctly in java. although code mirrors previous python solution, getting out of bounds exception in if input_str[i-1] == input_str[i] line. there different behavior in python loop might causing discrepancy? test cases 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);         (int i=1; < s.length(); i++) {            if (s.charat(i-1) == s.charat(i)) {                s = s.substring(0, i-1) + s.substring(i+1, s.length());                = 0;            }            if (s.length() == 0) {                system.out.println("empty string");                return;            }         }         system.out.println(s);     } } 

and code same problem, using python 2.7.

input_str = raw_input() 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)]         = 0     if len(input_str) == 0:         print "empty string"         break  print input_str 

in java loop, s.length() recalculated every iteration. in python, len(input_str) calculated once , not reflect correct length after you've modified input_str in if block.

similarly, assigning i = 0 not work way want to. i take on next value in xrange, ignoring attempted reset of value.


Comments