简体   繁体   中英

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 eg 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)
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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM