[英]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. 我正在处理HackerRank上的一些问题,我想我会尝试在Python中实现与我已经在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. 尽管我的代码几乎完全反映了我以前的Python解决方案,但是在if input_str[i-1] == input_str[i]
行中出现了超出范围的异常。 Is there different behavior in a Python loop that might be causing this discrepancy? Python循环中是否有其他行为会导致这种差异? 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. 这是针对相同问题的代码,但是使用的是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. 在Java循环中,每次迭代都会重新计算s.length()
。 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. 在Python中, len(input_str)
仅计算一次,并且在if
块中修改input_str
后不能反映正确的长度。
Similarly, assigning i = 0
does not work the way you want it to. 同样,分配i = 0
并不能达到您希望的方式。 i
will take on the next value in the xrange
, ignoring your attempted reset of its value. i
将采用xrange
的下一个值,而xrange
尝试重置其值。
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. 更好的解决方案是将算法更改为仅对input_str
一次迭代的算法。 In which case, you get O(n)
execution time. 在这种情况下,您将获得O(n)
执行时间。 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: 我将建立在funaquarius24上,甚至不使用索引:
input_str = raw_input()
result = input_str[0]
for c in input_str[1:]:
if c != result[-1]:
result += c
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.