Home > Blockchain >  Recursively find number of lowercase letters in a string
Recursively find number of lowercase letters in a string

Time:10-25

I'm trying to recursively find the number of lowercase letters in a string with low and high indices that determine which part of the string needs to be considered: def count_lowercase(s, low, high). My code stops going through the string once it hits an uppercase letter or a space because of if s[count] == s[count].lower() and s[count] != ' ' but I'm having trouble figuring out how to get it to continue. Any help is greatly appreciated!

My code

def count_lowercase(s, low, high):
    def countfunc(s2=s[low: high 1], count=0):
        if count > high:
            return count
        else:
            if s[count] == s[count].lower() and s[count] != ' ':
                return countfunc(s2, count 1)
        return count
    return countfunc()

CodePudding user response:

If you are trying to find lowercase letter in a portion of a string, why don't you follow this approach:

import re

def count_lowercase(s, low, high):
    return len(re.findall("[a-z]", s[max(0,low):min(high, len(s))]))

Follow up: if you cannot use any module:

def count_lowercase(s, low, high):
    s = s[max(0,low):min(high, len(s))].strip(" ")
    return sum([x==x.lower() for x in s])

CodePudding user response:

In the case of there being an uppercase or space is not handled, the count is immediately returned if it is not lowercase and is not a space.

Don't use the count as the index but keep it separate.

def count_lowercase(s, low, high):
    def countfunc(s2=s[low: high 1], count=0, index=0):
        if index > high:
            return count
        else:
            if s[index] == s[index].lower() and s[index] != ' ':
                return countfunc(s2, count 1, index 1)
            else:
                return countfunc(s2, count, index 1)
        return count
    return countfunc()

Think about if the code reaches a letter that is either a space or is uppercase, your if statement is false and isn't handled, going straight to return count. If you throw in an else for handling uppercases/spaces and still use count as an index, it will increase to go to the next index even when reaching an uppercase letter or a space.

Keep them separate and add the else!

  • Related