简体   繁体   English

Python 字符串中最长的字符序列

[英]Python longest character sequence in a string

I'm studying python and got an issue with a lab.我正在研究 python 并遇到了实验室问题。 Need to calculate the longest sequence of an s char in a string, can only use basic tools like for loops.需要计算字符串中一个s char的最长序列,只能使用for循环之类的基本工具。

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.我提出的代码有效,但感觉就像我使用了不适当的逻辑,添加了一个带有额外空间的sequence_extended变量。 However without this extension provided the sequence is eg sssdssss the calculation only works for the first sequence.然而,如果没有这个扩展,如果序列是例如sssdssss ,则计算仅适用于第一个序列。

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.以防万一其他人有这样的实验室要解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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