Skip to content

Question 44

Let input s be a string with uppercase alphabet characters. Complete function count_alpha() using valid Python expressions/statements so that it returns a dictionary whose keys are all the characters in s, and the corresponding values are the number of times the characters appear in s.

1
2
3
4
5
6
7
def count_alpha(s):
    output = dict()
    for c in _____1_____:
        if _____2_____:
            output[c] = _____3_____
        output[c] = _____4_____
    return output

Here is a sample run:

>>> print(count_alpha("QUEUE"))
{'Q': 1, 'U': 2, 'E': 2}
>>> print(count_alpha("BANANAS"))
{'B': 1, 'A': 3, 'N': 2, 'S': 1}

Note that your code needs to be syntactically correct to gain marks. You cannot use any semi-colon(;) and we will deduct marks if your answer is too long.

Model Solution
1
2
3
4
5
6
7
def count_alpha(s):
    output = dict()
    for c in s:
        if not c in output:
            output[c] = 0
        output[c] = output[c] + 1
    return output
  • Blank 1: s
    • Iterate through each character in s, keeping the character at each iteration in c
  • Blank 2: not c in output
    • Check if character c is one of the keys in output (i.e., is there a count for the number of times c appears in s)
  • Blank 3: 0
    • Here, we create a key-value pair with the current c as the key, and initialize it to 0 first before counting the first time this same c is encountered in the next line.
  • Blank 4: output[c] + 1
    • Because the assignment operator = is already given to you, += 1 to make output[c] += 1 is not a correct answer.