So I need to know if in a string which contains only '1's and '0's has 7 of one of those in a row. My first thought was to iterate through the string like so:
for i in inp:
if count == 6:
answ = True
this = i
if this == other:
count =1
other = this
else:
other = this
count = 0
But it randomly gives out a wrong answer. My next idea was to use regex (.)\1{7,}
like this:
pattern = re.compile(r'(.)\1{7,}')
found = re.search(pattern, inp)
if found != None:
answ = True
But it still sometimes makes mistakes. Anyone has any ideas on why that would happen? Regex was taken from here
CodePudding user response:
I'm sure that there is a regex pattern that could work for this, but like many other programmers, I've never quite figured out how regex works. However, the following script should be able to determine if there is a substring that matches your description.
current = None
current_len = 0
answer = False
for i in inp:
if i == current:
current_len = 1
if current_len >= 7:
answer = True
break
else:
current = i
current_len = 1
print(answer)
Obviously, the answer variable in this case would be True
if there are 7 consecutive characters and False
if there aren't. Hopefully this helps :)
CodePudding user response:
cheper's comment actually worked flawlessly. I don't know why I didn't think of it sooner
Until you can prove it's a bottleneck, I wouldn't do anything more complicated than
'1111111' in inp or '0000000' in inp
CodePudding user response:
I like @chepner's comment and I might start with that as echoed by @ive. Since you started a regex based answer, you might also try:
import re
def check_line(line):
return re.search(r"0{7,}|1{7,}", line) is not None
tests = [
"00001111",
"00000001",
"01111111",
"100000001111",
"10000100001111"
]
for test in tests:
print(test, check_line(test))
That should give you:
00001111 False
00000001 True
01111111 True
100000001111 True
10000100001111 False
CodePudding user response:
Can't you follow this approach?
def check_line(l, target = 7):
return l if any(map(lambda y: any(map(lambda x:len(x) == target, l.split(y))), ["1","0"])) else ""
print(check_line("00000001111"))
print(check_line("000000001111"))
OUTPUT
00000001111
This solution works if you want sequences of exactly 7 elements: if you need 7 or more, chepner approach is the cleanest.