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
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.
I believe you are wasting a lot of time and system resources by doing it that way. A better solution would be to change the algorithm into one that only iterates input_str
only once. In which case, you get O(n)
execution time. My edited code looks thus:
input_str = input()
input_strR = input_str[0]
for i in range(1, len(input_str)):
if input_str[i-1] != input_str[i]:
input_strR = input_strR + input_str[i]
if len(input_str) == 0:
print ("Empty String")
break
print (input_strR)
In this case, a new variable was introduced and all first characters were added while duplicates were dropped.
I would build on funaquarius24 and not even use indexes:
input_str = raw_input()
result = input_str[0]
for c in input_str[1:]:
if c != result[-1]:
result += c
print(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.