I'm working on this LeetCode problem here, and I'm implementing a brute force approach as well as an iterative approach. The iterative approach works fine, but my brute force approach seems to have hit an edge case. I want to determine whether a string has 3 consecutive numbers and return the highest 3 consecutive numbers in it. My code is as follows:
class Solution:
def largestGoodInteger(self, num: str) -> str:
if str(999) in num:
return "999"
elif str(888) in num:
return "888"
elif str(777) in num:
return "777"
elif str(666) in num:
return "666"
elif str(555) in num:
return "555"
elif str(444) in num:
return "444"
elif str(333) in num:
return "333"
elif str(222) in num:
return "222"
elif str(111) in num:
return "111"
elif str(000) in num:
return "000"
else:
return ""
For some reason, the string 101010
returns "000"
even though 000
is not sequential in the string. I figured that the in
operator may be evaluating the string 000
as an array and iterating over each element in the string, but the operator does not appear to do that according to the docs. As such, why does 000
get returned instead of ""
?
It turns out that the issue didn't have anything to do with the in
operator, but rather how Python evaluates string conversion. No matter how many zeroes you pass to str()
, it returns a single zero as a string. Therefore, str(000)
returned "0"
and since the single 0
exists in the string, the statement returned True
. Changing it to "000" in str(num)
fixed the issue.