Write a code that calculates the number of consecutive appearances of the same character in a string after one string is entered.
Write to print out the most consecutive appearances.
s=input()
maxi=0
count=0
last=s[0]
for c in s:
if last == c:
count +=1
last=c
else:
if maxi<= count:
maxi=count
last=c
count= 1
print(maxi)
I wrote it as above, but the most cases are not printed. I ask for your opinion.
python
The if maxi<= count:
condition is a problem.
last
and count
should always be set when else
.
If count
is not set to 1, the number containing the number of previous consecutive characters is calculated.
If last
is not set, you can calculate with the same character even if the previous character is different.
The longest consecutive characters may be at the end, so you should make another maximum comparison outside the for
statement.
Therefore, it can be modified as below.
s = input()
maxi = 0
count = 0
last = s[0]
for c in s:
if last == c:
count += 1
else:
if maxi < count:
maxi = count
count = 1
last =c
if maxi < count:
maxi = count
print(maxi)
s = input()
maxi = 0
count = 1
for i in range(len(s)-1):
if s[i] == s[i+1]:
count += 1
else:
count = 1
if maxi < count:
maxi = count
print(maxi)
© 2025 OneMinuteCode. All rights reserved.