【发布时间】: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