Stikka
Stikka

Reputation: 27

Python longest character sequence in a string

I'm studying python and got an issue with a lab. Need to calculate the longest sequence of an s char in a string, can only use basic tools like for loops.

The code that I've come up with works, but it feels like I'm using an inappropriate logics adding a sequence_extended variable with an extra space. However without this extension provided the sequence is e.g. sssdssss the calculation only works for the first sequence.

Might there be a way to avoid that extension? I've tried looking for an idea, but the solution is usually to use the functions we're not allowed to use yet, such as lists etc.

sequence = input('enter a line: ')
sequence_extended = sequence + ' '
counter = 0
final_counter = 0

for symbol in sequence_extended:
  if symbol == 's':
    counter += 1
    
  else:
    if counter > final_counter:
        final_counter = counter
        counter = 0


print("The longest sequence of 's':", final_counter)

Upvotes: 0

Views: 783

Answers (2)

Stikka
Stikka

Reputation: 27

As a matter of fact, I've come up with an even less complicated option:

sequence = input('enter a sequence: ')

first_counter = 0
second_counter = 0

for symbol in sequence:
  if symbol == 's':
    first_counter += 1
  if symbol != 's':
    first_counter = 0  
  if second_counter < first_counter:
    second_counter = first_counter
print("the longest sequence of 's':", second_counter)

It seems to be an optimal solution for the matter. Just in case someone else has a lab like this to solve.

Upvotes: 0

Mick
Mick

Reputation: 796

sequence = "sssdssss"
max_len = 0

for i in range(len(sequence)):
    if sequence[i] == "s":
        j = i
        length = 0
        while j < len(sequence) and sequence[j] == "s":
            length += 1
            j += 1
        if length > max_len:
            max_len = length

print("The longest sequence of 's':", max_len)

Upvotes: 1

Related Questions