ORM ORM - 1 month ago 9
Python Question

Counting uppercase letters in a list excluding the first capital in a word

So my function must take a list of strings and return the total number of capital letters that appear in positions other than the beginning of a word. Also to break this problem into a sub problem, it needs a second function that takes a single word and returns the number of capital letters that appear in positions other than the beginning of that word. So far I have a function that works, but I have been told it needs to be done better and I am not quite sure how to do that.

def count_strange_caps(words):
if words[0].isupper():
count = abs(1 -sum(1 for c in words if c.isupper())
elif words[0].islower():
count = abs(sum(1 for c in words if c.isupper()))
return count

def total_strange_caps(words):
total_count = 0
for word in words:
if word[0].isupper():
total_count -= 1
for letter in word:
if letter.isupper():
total_count += 1
return total_count


My teacher told me to combine the two list comprehensions in count_strange_caps as they are basically the same code and use the code from count_strange_caps in the inner for loop for the second function.

print(total_strange_caps(["Five","FiVe","fIVE"]))
print(total_strange_caps(["fIVE"]))
print(count_strange_caps("fIVE"))


These are the types of tests it needs to pass and if anyone could help me with a solution using more rudimentary concepts it would be much appreciated. I can not use numpy if that makes a difference.

Answer

You may use str.isupper() and sum() to achieve this. Using these, the function definition of count_strange_caps() should be like:

def count_strange_caps(word):
     return sum(my_char.isupper() for my_char in word[1:]) # word[1:] to skip the first character

Sample run:

>>> count_strange_caps('HeLlo')
1
>>> count_strange_caps('HeLLo')
2
>>> count_strange_caps('heLLo')
2

Also, your total_strange_caps() can be simplified using sum() as:

def total_strange_caps(words):
    return sum(count_strange_caps(word) for word in words)

Sampl run:

>>> total_strange_caps(['HeLlo', 'HeLLo', 'heLLo'])
5