How do I get the code to count the number of indexes as well as Cap count

Viewed 44

I have written the Python code to count the number of Capital letters in any given argument, but it gives the outcome of 0 indexes no matter what is given for input. For example: for 'Hello', it returns 1 0 Which is correct, but it then gives incorrect answers after:

    'Hello World. Its a great day!'

3 <- expected  3 <- output
19 <- expected 0 <- output

    'aAe_0Ia eIaoeUYQ!'

6 <- expected 6 <- output
57 <- expected 0 <- output

Here's my code:

import sys
sent = sys.argv[1:]
count = 0
for i in str(sent):
    if i.isupper():
       count = count + 1
print(count)
s = str(sys.argv[1:])
def c_upper(s):
    upper = 0
    return upper
    for char in s:
        if char.isupper():
            upper += 1
print(c_upper(sys.argv[1:]))
4 Answers

Your c_upper() function has a return statement before your for loop. So it's always going to return 0.

I am not 100% sure that this is what you're looking for but you can get the index when using range for loop.

    string = 'aAe_0Ia eIaoeUYQ!'
    count = 0
    index = 0
    for x in range(len(string)):
        if string[x].isupper():
            count += 1
            index += x
    print(count, index)
    >>> 6 57

I'm not sure I understood the question 100% but this gives the right result. This function counts the number of uppercase letters, sum all indexes and return both values:

def c_upper(s: str) -> Tuple[int, int]:
    indexes_table = list(i for i, v in enumerate(s) if v.isupper())
    return len(indexes_table), sum(indexes_table)


print(*c_upper('Hello World. Its a great day!'))
# 3 19
print(*c_upper('aAe_0Ia eIaoeUYQ!'))
# 6 57

the task can also be solved by using regex:

import re
txt = 'aAe_0Ia eIaoeUYQ!'
ind = count = 0
for match in re.finditer(r'[A-Z]', txt):
    ind, count = ind + match.start(), count +1 # increment counters
print(count, ind)

result: 6 57

Related