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.
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
- Blank 1:
s- Iterate through each character in
s, keeping the character at each iteration inc
- Iterate through each character in
- Blank 2:
not c in output- Check if character
cis one of the keys inoutput(i.e., is there a count for the number of timescappears ins)
- Check if character
- Blank 3:
0- Here, we create a key-value pair with the current
cas the key, and initialize it to0first before counting the first time this samecis encountered in the next line.
- Here, we create a key-value pair with the current
- Blank 4:
output[c] + 1- Because the assignment operator
=is already given to you,+= 1to makeoutput[c] += 1is not a correct answer.
- Because the assignment operator