给定一个字符串,找出python

时间:2015-05-15 12:49:40

标签: python

我是python的新手。试图解决一些一般的编程问题。作为其中的一部分,我尝试了很多方法来实现以下目标。例如,我有一个像这样的字符串

s = "abbcddeeffffcccddddggggghhhiaajjjkk"

我想找出给定字符串中每个字符的最大连续出现次数。在上面的例子中,输出应该是,

a - 2
b - 2
c - 3
d - 4
e - 2
f - 4
g - 5 etc

任何帮助表示感谢,谢谢!

4 个答案:

答案 0 :(得分:3)

>>> 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

答案 1 :(得分:1)

您可以使用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)

答案 2 :(得分:1)

有点老,但是很有趣。

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)]

答案 3 :(得分:0)

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
}