如何计算连续的大写和小写字母?

时间:2018-10-01 14:14:58

标签: python

例如,我键入 word = "aaBBaac" 我将如何获得输出

[2,2,3]

这是我已经拥有的:

word = input()
count = 0
for i in range(0,len(word)):
    if word[i-1].islower()==word[i].islower()==True:
        count+=1
print(count)

3 个答案:

答案 0 :(得分:2)

您可以使用itertools.groupby解决此问题:

from itertools import groupby

word = "aaBBaac"
ret = []
for _key, group in groupby(word, key=lambda x: x.islower()):
    ret.append(len(tuple(group)))
print(ret)  # [2, 2, 3]

groupby发出keygroup相同的所有元素。在此示例中,每次有问题的字母大小写发生变化时,key函数都会从True变为False(反之亦然)。

您可以将其打包成列表信息:

ret = [sum(1 for item in group)
       for _, group in groupby(word, key=str.islower)]

(使用sum(1 for item in group)代替len(tuple(group))key=str.islower代替我上面使用的lambda表达式可能更高效,更优雅)。

答案 1 :(得分:0)

word= input() 
consec_cnt_lst = []
idx = 0

这里有两种构造代码的方式。 注意idx的递增方式。


1)

while idx < len(word):

    if 'A' <= word[idx] <= 'Z':
        upper_cnt = 0
        while idx < len(word) and 'A' <= word[idx] <= 'Z': 
            upper_cnt +=1
            idx+=1

        consec_cnt_lst.append(upper_cnt)

    elif  'a' <= word[idx] <= 'z':  
        lower_cnt = 0
        while idx < len(word) and 'a' <= word[idx] <= 'z':
            lower_cnt +=1
            idx+=1

        consec_cnt_lst.append(lower_cnt)

    else:
        idx+=1      


2)

while idx < len(word):
    upper_cnt = 0
    while idx < len(word) and 64 < ord(word[idx]) < 91: #ASCII value of  A = 65 and Z = 90
        upper_cnt +=1
        idx+=1

    if upper_cnt > 0:
        consec_cnt_lst.append(upper_cnt)
        idx-=1

    lower_cnt = 0
    while idx < len(word) and 96 < ord(word[idx]) < 123: #ASCII value of  a = 97 and Z = 122
        lower_cnt +=1
        idx+=1

    if lower_cnt > 0:
        consec_cnt_lst.append(lower_cnt)
        idx-=1

    idx+=1   


print(consec_cnt_lst)

输出

# AAAnnnnZZz --> [3, 4, 2, 1]
# AAAnn23nnZZz --> [3, 2, 2, 2, 1]
# aaaBBaaa --> [3, 2, 3]

答案 2 :(得分:0)

我会说,公认的答案肯定是正确的方法。但是由于它被要求在不导入任何内容的情况下执行此操作,所以我认为我可以尝试一个。这是我想出的:

my_string = "aaBBaac"
my_list = []

iterate = 0
total = 0

for x in my_string:
    if iterate == len(my_string) - 1:
        #this is for last character in the list
        if (x.isupper() and my_string[iterate - 1].islower()) or (x.islower() and my_string[iterate - 1].isupper()):
            my_list.append(1)
        else:
            total += 1
            my_list.append(total)
    elif (x.islower() and my_string[iterate + 1].islower()) or (x.isupper() and my_string[iterate + 1].isupper()):
        #is the current and next character the same case?
        total += 1
    else:
        #current and next character must be different
        total += 1
        my_list.append(total)
        total = 0
    iterate += 1

print (my_list)

它正在查看字符串中的当前字符,并将其与下一个进行比较。如果当前字符和下一个字符相同,则将它们添加到total中;如果它们不相同,则将total添加到my_list并重置总计。第一个if是字符串中最后一个字符的特殊情况。