[英]Given a string, find out the highest repeated characters count in python
試圖解決一些一般的編程問題。 作為其中的一部分,我嘗試了很多方法來實現以下目標。 例如,我有一個這樣的字符串
s = "abbcddeeffffcccddddggggghhhiaajjjkk"
我想找出給定字符串中每個字符的最大連續出現次數。 在上述情況下,輸出應如下所示,
a - 2
b - 2
c - 3
d - 4
e - 2
f - 4
g - 5 etc
>>> s = "abbcddeeffffcccddddggggghhhiaajjjkk"
>>> for x in sorted(set(s)):
... i = 1;
... while x * i in s:
... i += 1
... print x, "-", i - 1
...
a - 2
b - 2
c - 3
d - 4
e - 2
f - 4
g - 5
h - 3
i - 1
j - 3
k - 2
您可以使用itertools.groupby
找出每組重復字母的長度,然后按組的長度進行排序。
>>> s = "abbcddeeffffcccddddggggghhhiaajjjkk"
>>> from itertools import groupby
>>> repeats = sorted([(letter, len(list(group))) for letter, group in groupby(s)], key = lambda i: i[1], reverse = True)
>>> repeats
[('g', 5), ('f', 4), ('d', 4), ('c', 3), ('h', 3), ('j', 3), ('b', 2), ('d', 2), ('e', 2), ('a', 2), ('k', 2), ('a', 1), ('c', 1), ('i', 1)]
>>> repeats[0]
('g', 5)
有點舊線程,但有助於樂趣。
s = 'aaaabbbbbcdddddddddddd1111000000000000000'
string_set = list(set(list(s)))
string_count_dict = {key: s.count(key) for key in string_set}
print(sorted(string_count_dict.items()))
輸出:
[('0', 15), ('1', 4), ('a', 4), ('b', 5), ('c', 1), ('d', 12)]
CoryKramer 先生針對該問題給出了非常出色且非常專業的解決方案。 但我認為這是一個面試問題。 所以我只用 1 個 for 循環來完成任務。 這是完整的解決方案。 該代碼是不言自明的。
在 Python 中:
a = "GiniiGinnnaaaaProtiiiijayyyyyyyyyyyyyyyi"
count = 0
maxcount = 0
lastCharacter = ""
longestcharacter = ""
for ch in a:
if(ch == lastCharacter):
count += 1
if(count > maxcount):
maxcount = count
longestcharacter = ch
else:
count = 1
lastCharacter = ch
print(longestcharacter)
print(maxcount)
在 Java 中:
class test2{
public static void main(String[] args) {
String aa = "GinaaaaaaaaaaaaaaaPPPPPProtttttijayi";
char[] ca = aa.toCharArray();
char lastchar = 0;
int maxcount = 0 ;
int count = 0 ;
char longestContinuousCharacter = 0;
for( char ch :ca) {
if(ch == lastchar) {
count++ ;
if(count > maxcount) {maxcount = count ;longestContinuousCharacter = ch;}
}//if
else {
lastchar = ch;
count =1 ;
}//else
}//for
System.out.println("longestContinuousCharacter => "+ longestContinuousCharacter);
System.out.println("maxcount => " + maxcount );
}//main
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.