kaiva
kaiva

Reputation: 11

Counting lowercase using recursion and low and high parameters

So im trying to create a recursive function that can count the amount of lowercase numbers in a word. This is what I have so far and im having difficulty implementing the low and high parameters that determine the range the function is checking.

 def count_lowercase(s, low, high):
    count = 0
    if len(s) == 0:
        return 0
    elif s[low].islower():
        count+=1
    count_lowercase(s[low+1:high])

    return count 

Upvotes: 0

Views: 558

Answers (2)

blhsing
blhsing

Reputation: 106768

You can use a function that checks if the first character is lowercase and recursively adds the number of lowercase characters in the rest of the string, or returns 0 if the string is empty:

def count_lowercase(s):
    return len(s) and s[0].islower() + count_lowercase(s[1:])

Upvotes: 0

Mikael Brenner
Mikael Brenner

Reputation: 357

You need to have the recursion step on the return, so they get called for every size until done.

This code does it, high defines the position of limit:

def count_lowercase(s, high=0):
    count = 0

    if len(s) == 0:
        return 0
    if high == 0:
        high = len(s)
    if s[0].islower():
        count+=1
    return count + count_lowercase(s[1:high+1])

Upvotes: 1

Related Questions