gpt4 book ai didi

python-3.x - 检查字符串中连续出现了多少次[已解决]

转载 作者:行者123 更新时间:2023-12-04 08:15:46 24 4
gpt4 key购买 nike

我想显示最常出现的数字或字母
在给定的字符串或数字或两者中连续
例子
s = 'aabskeeebadeeee'
输出: e 连续出现 4 次
我想过设置字符串然后为每个元素循环字符串
检查是否与元素集元素相等,如果是,则计数 =+1 并检查是否
在它旁边不等于将计数器值添加到具有相同索引的列表中
设置,如果值大于现有值,则将计数器值添加到 li 列表。
问题是错误索引超出或范围,尽管我想我正在看它。

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')
已解决
我不想使用任何库,所以我又坐了下来,尽管它让我头疼,但我还是找到了解决方案:-)。
 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

最佳答案

这是一个 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

关于python-3.x - 检查字符串中连续出现了多少次[已解决],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65712212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com