-3

Here is the code and im struggling to understand the line 5 and 6. I know how isupper() works but i cant understand the combinations going on.

def IndexWords(InputText):
    words = 0
    count = 2
    for i in range(len(InputText)):
        for word in InputText[i].split()[1:]:
            CapitalizationCheck = list(word.strip(','))[0].isupper()
            if CapitalizationCheck == True:
                print('%s:%s' % (count,word))
                words +=1
            count += 1
        count += 1

    if words == 0:
        print('None')

IndexWords(input().split('.'))

This code works just fine but there is too much going on in it(mybe too much for me)

Elsahn_go
  • 1
  • 1
  • 2
    This is dreadful code. You're better off learning from elsewhere. – Andras Deak -- Слава Україні Jun 12 '23 at 11:09
  • 1
    There is too much going on! Everything from using capitalisation in variables names to splitting and slicing that can cause things to break easily. But the underlying logic is pretty simple. Iterate over every word in text while clearing all whitespace, convert every word to list and check if first item in the list is capitalised.. – Geom Jun 12 '23 at 11:11
  • `for word in InputText[i].split()[1:]:` split the input string into a list on spaces and discard the first word. `list(word.strip(','))` strip out any commas and turn the word into a list of individual characters, the `[0].isupper()` checks if the first letter is uppercase. Probably worth noting: this code isn't very good. – Jared Smith Jun 12 '23 at 11:11
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Jun 12 '23 at 14:51

1 Answers1

-1

There is too much going on! Everything from using capitalisation in variables names to splitting and slicing that can cause things to break easily.

A much more elegant solution would be something like this:

def count_capitalized_words(text):
    words = text.split()
    count = sum(1 for word in words if word.istitle())
    return count

text = "This is an Example Text. It Contains Capitalized Words."
print(count_capitalized_words(text))

Output:

7
Geom
  • 1,491
  • 1
  • 10
  • 23
  • This does not produce the same output as OP's code – DarkKnight Jun 12 '23 at 11:35
  • That was not the intention. The snippet is simplifying the capitalisation check so that the OP can understand it and build on top of it. This was not meant to be a refactor.. – Geom Jun 12 '23 at 14:10