0

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)
7
  • 1
    You're not allowed to use dictionaries right? Commented Jan 9, 2021 at 4:58
  • @Mick aye, exactly Commented Jan 9, 2021 at 4:59
  • 1
    It's an easy question, hold on Commented Jan 9, 2021 at 5:00
  • 1
    You need to add a line for what happens if the last symbol is an "s". As you have it now, final counter is only updated if the last character is not an "s" ( why adding the extra space at the end fixes it). Commented Jan 9, 2021 at 5:03
  • 1
    are you allowed to use a while loop? I can make it a for loop instead if not Commented Jan 9, 2021 at 5:04

2 Answers 2

1
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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! Totally works and I get the logics. Appreciate it!
No problem, happy coding!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.