Find the length of the longest sequence consisting of R characters
A text file consists of no more than 10^6 characters L, D, and R. Determine the length of the longest sequence consisting of the characters R.
I must say, I'm new to Python, so all I could write was this:
f = open("zadanie24_2.txt")
s = f.readlines()
m = 0
for i in s:
if s(i) == "R" and s(i + 1) == "RR":
m+=1
print(m)
Somewhere in the Internet I found this code, I substituted my values in it, but again nothing came out
# откроем файл на чтение
F = open ('zadanie24_2.txt', 'rt')
# T - список файла F
T = F.read ().split ()
K = 1 # K - число одинаковых чисел
A = [] # список длин цепочек одинаковых чисел
for i in range (0, len (T) - 1) :
#print (T [i], end = '')
if T [i] == T [i + 1] :
K += 1
else :
A += [K]
K = 1
A += [K]
F.close ()
R = open ('result.txt', 'wt')
R.write (str (max (A)))
R.close ()
print ('Файл result.txt записан')
Help who can
2 answers
-
Indexes should be written in square brackets, not in round brackets
-
for i in s
so you go through all the elements, and you need all the indexes. it should be like thisfor i in range(len(s) - 1)
-
s[i + 1] == "RR"
you take one element and compares it to two. it should be like thiss[i + 1] == "R"
-
You do not save or reset the value of
m
f = open("zadanie24_2.txt")
s = f.read()
m = 1
maxlen = 0
for i in range(len(s) - 1):
if s[i] == "R" and s[i + 1] == "R":
m += 1
if mexlen < m:
maxlen = m
else:
m = 1
if maxlen == 0 and "R" in s:
maxlen = 1
print(maxlen)
Let's go through the indexes of the string. Met R-remembered the index of the beginning. Met not R-calculated the length of the series.
r = False
maxlen = 0
for i in range(len(s)+1):
if i<len(s) and s[i] == "R":
if not r:
start = i
r = True
else:
if r:
maxlen = max(maxlen, i - start)
r = False
print(maxlen)