Recursively return if the number of lowercase letters in a string is even

Viewed 41

I'm trying to write a recursive function that returns true if the number of lowercase letters in a string is even. This is what I have until now:

def is_number_of_lowercase_even(s,low,high):
if (low==high):
    return False
if low<high:
    left = s[low].islower()       
    return left and not is_number_of_lowercase_even(s,low+1,high)

I have to stick to the function definition above. Not sure what I'm doing wrong.

1 Answers

Something like this? Divide the range in half. If both halves are even or both halves are odd then the total is even.

def f(s, low, high):
  if low == high:
    return not s[low].islower()

  mid = low + (high - low) // 2
  left = f(s, low, mid)
  right = f(s, mid + 1, high)

  return (left and right) or (not left and not right)

strs = [
  "Abc",
  "ABc",
  "asdf",
  "aSdF",
  "ASdf",
  "AsDF"
]

for s in strs:
  print(s, f(s, 0, len(s) - 1))

"""
('Abc', True)
('ABc', False)
('asdf', True)
('aSdF', True)
('ASdf', True)
('AsDF', False)
"""
Related