ORM ORM - 1 year ago 87
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.


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 Source

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')
>>> count_strange_caps('HeLLo')
>>> count_strange_caps('heLLo')

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'])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download