【问题标题】:Check how many consecutive times appear in a string检查字符串中连续出现的次数
【发布时间】:2021-01-14 01:40:28
【问题描述】:

我想显示一个出现频率最高的数字或字母 在给定的字符串或数字或两者中连续。

例子:

s= 'aabskeeebadeeee'
output: e appears 4 consecutive times

我考虑过设置字符串然后为每个元素循环字符串以检查是否与元素 set element if so count =+1 并检查它旁边是否不相等将计数器值添加到具有相同索引的列表中set, if is add counter value to li list if value is greater than existing.

问题是错误索引超出或范围,虽然我想我正在看它。

s = 'aabskeeebadeeee'

c = 0
t = list(set(s)) # list of characters in s
li=[0,0,0,0,0,0]  # list for counted repeats
print(t)
for x in t:
    h = t.index(x)
    for index, i in enumerate(s):
        maximus = len(s)
        if i == x:
            c += 1
            if index < maximus:
                if s[index +1] != x:  # if next element is not x
                    if c > li[h]:   #update c if bigger than existing
                        li[h] = c
                    c = 0
            else:
                if c > li[h]:
                    li[h] = c


for i in t:
    n = t.index(i)
    print(i,li[n])

print(f'{s[li.index(max(li))]} appears {max(li)} consecutive times')

【问题讨论】:

  • 我认为您的做法不正确。您如何期望该字符串中出现“0”?您是否想获得出现次数最多的字符,即“e”。我不明白这个问题
  • 不得不编辑,打错字了。是的,它应该打印 'e', s= 'aabskeeebadeeee' 输出:e 连续出现 4 次。最后 4 个是最长的。
  • 哦,这是一道简单的题,一次就可以完成,我来教你

标签: python-3.x string


【解决方案1】:

这是一个 O(n) 时间,O(1) 空间解决方案,它通过返回较早看到的字符来打破平局:

def get_longest_consecutive_ch(s):
    count = max_count = 0
    longest_consecutive_ch = previous_ch = None
    for ch in s:
        if ch == previous_ch:
            count += 1
        else:
            previous_ch = ch
            count = 1
        if count > max_count:
            max_count = count
            longest_consecutive_ch = ch
    return longest_consecutive_ch, max_count

s = 'aabskeeebadeeee'
longest_consecutive_ch, count = get_longest_consecutive_ch(s)
print(f'{longest_consecutive_ch} appears {count} consecutive times in {s}')

输出:

e appears 4 consecutive times in aabskeeebadeeee

【讨论】:

    【解决方案2】:

    Regex 在这里提供了一个简洁的解决方案:

    inp = "aabskeeebadeeee"
    matches = [m.group(0) for m in re.finditer(r'([a-z])\1*', inp)]
    print(matches)
    matches.sort(key=len, reverse=True)
    print(matches[0])
    

    打印出来:

    ['aa', 'b', 's', 'k', 'eee', 'b', 'a', 'd', 'eeee']
    eeee
    

    这里的策略是使用re.finditer 和正则表达式模式([a-z])\1* 查找所有相似字符的岛。然后,我们将结果列表按长度降序排序以找到最长的序列。

    【讨论】:

    • 这个解决方案的时间复杂度为 O(n*logn),因此不是最优的
    • 感谢您的宝贵意见。我永远不会再将正则表达式用于任何事情。
    • Regex 不是问题,是 group() 和 sort()。不客气
    • @Mick 对于较大的N 值,O(N*lgN) 在大多数设置中都会提供合理的性能(除非需要非常高的性能)。
    • 我的答案可以改进,而不是对结果列表进行排序,只需沿着列表走一次并跟踪看到的最宽的字符串。然后,返回最宽的字符串。
    【解决方案3】:

    或者,您可以利用itertools.groupby() 的强大功能来解决此类问题(用于快速计算groups 中的类似项目。[注意,这可以应用于一些更广泛的情况,例如数字]

    from itertools import groupby
    
    >>> char_counts =  [str(len(list(g)))+k  for k, g in groupby(s)]
    >>> char_counts
    ['2a', '1b', '1s', '1k', '3e', '1b', '1a', '1d', '4e']
    >>> max(char_counts)
    '4e'
    
    # you can continue to do the rest of splitting, or printing for your needs...
    >>> ans = '4e'      # example
    >>> print(f' the most frequent character is {ans[-1]}, it appears {ans[:-1]} ')
    

    输出: 出现频率最高的字符是 e,出现 4

    【讨论】:

      【解决方案4】:

      此答案是由 OP Ziggy Witkowski 在 CC BY-SA 4.0 下以 edit 对问题 Check how many consecutive times appear in a string 发布的。

      我不想使用任何库。

      s = 'aabskaaaabadcccc'
      
      lil = tuple(set(s)) # Set a characters in s to remove duplicates and
      then make a tuple
      
      li=[0,0,0,0,0,0]  # list for counted repeats, the index of number
      repeats for character
                      # will be equal to index of its character in a tuple
      
      
      for i in lil:    #iter over tuple of letters
          c = 0        #counter
          h= lil.index(i)  #take an index 
          for letter in s:            #iterate ove the string characters 
              if letter == i:         # check if equal with character from tuple
                  c += 1              # if equal Counter +1
                  if c > li[lil.index(letter)]:   # Updated the counter if present is bigger than the one stored.
                      li[lil.index(letter)] = c
              else:
                  c=0
                  continue
      
      m = max(li)
      
      for index, j in enumerate(li):              #Check if the are
      characters with same max value
          if li[index] == m:
              print(f'{lil[index]} appears {m} consecutive times') 
      

      输出:

      c appears 4 consecutive times 
      a appears 4 consecutive times 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-21
        • 2015-07-09
        • 1970-01-01
        • 2021-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多