使用递归计算python中的大写和小写字母

时间:2017-04-21 15:02:16

标签: python recursion tuples uppercase lowercase

我需要帮助提出这个python函数。 一个递归函数count_upper_lower(),它接受一个非空字符串作为参数,并返回一个元组,其中包含字符串中多少个字母的计数是大写的,有多少是小写的(按此顺序)。 例如

print (count_upper_lower(’Town Hall University’)) 

将返回

(3, 15)

这是我到目前为止所拥有的

def count_upper_lower(word):
    upper = 0
    lower = 0
    if word == "":
        upper = 0
        lower = 0
        return upper, lower
    elif word[0].isupper():
        upper = 1 + count_upper_lower(word[1:])
        return upper , lower


    elif word[0].islower():
        lower = 1 + count_upper_lower(word[1:])
        return upper , lower

    else:
        upper = 0 + count_upper_lower(word[1:])
        lower = 0 + count_upper_lower(word[1:])
        return upper, lower

我收到以下错误:

TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

5 个答案:

答案 0 :(得分:1)

我会使用循环和ascii。在ascii表65中,直到91是大写,97直到123是小写。

def count_upper_lower(word):
    upper = 0
    lower = 0
    for letter in word: #runs through all the letter if empty nothing happens
       if 65 <= ord(letter) <= 90:
           upper += 1
       elif 97 <= ord(letter) <= 122:
           lower += 1
    return upper,lower

这也是可能的。

def count_upper_lower(word):
    upper = 0
    lower = 0
    for letter in word: #runs through all the letter if empty nothing happens
       if letter.isupper():
           upper += 1
       elif letter.islower():
           lower += 1
    return upper,lower

答案 1 :(得分:1)

如果你想用两行代码来做:

lst = [1 if letter.islower() else 0 for letter in word if letter.islower() or letter.isupper()]
print (lst.count(0),lst.count(1))

答案 2 :(得分:1)

正如所指出的,您正在尝试向元组添加int,这就是您收到错误消息的原因。请考虑以下示例:

def count_upper_lower(word):
    if not word:
        return 0, 0
    else:
        upper, lower = count_upper_lower(word[1:])
        if word[0].isupper():
            return upper+1, lower
        elif word[0].islower():
            return upper, lower+1
        else:
            # make sure that this is what you want
            return upper, lower

这里,函数递归调用自身,直到字符串用完为止。 else case捕获的情况是字符既不是上部字符也不是下部字符(例如数字),在这种情况下,两个计数器都不会增加。

答案 3 :(得分:0)

在你的else块中,你试图将count_upper_lower()中返回的元组添加到一个数字中。

// Search
final Query query = new Query("#World");
final QueryResult result = twitter.search(query);

int numTweetsFromHashtag = 0;
for (Status status : result.getTweets())
{
    // If we've met our limit for the hashtag stop
    numTweetsFromHashtag++;
    if (numTweetsFromHashtag > 5) break;

    // Create a limit of tweets to get for the user
    final Paging paging = new Paging(1, 10 /*< num tweets per user*/);
    // Get that number of tweets
    final List<Status> tweets = twitter.getUserTimeline(
        status.getUser().getScreenName(), paging
    );

    // Loop over all the tweets we just got and print them
    for(final Status tweet : tweets)
    {
        System.out.println(tweet.getText());
    }
}

答案 4 :(得分:0)

使用tuple是一个问题,因为它是一个不可变的数据结构。改为使用list

def count_letters(phrase):
    if phrase:
        letter = phrase[0]
        result = count_letters(phrase[1:])
        if letter.isupper():
            result[0] += 1
        elif letter.islower():
            result[1] += 1
        return result
    else:
        return [0, 0]


>>> count_letters("LaLaa")
[2, 3]