I have a coding assignment where I need to create a program that checks for the number of times a dictionary of names have the letters R, M, A, K and C. So in this case I have this dictionary:
dict = {"Renata", "Maciek", "Marek", "Karolina", "Marcel}
I need to create a loop that checks for all of those letters in all of the names in the dictionary one by one. Once it is done, it needs to put the results in a list and return the list at the end of the program. So the result will look like
R - 4 M - 2 A - 3. (numbers are just to give an example) K - 5 C - 6
This is what I have so far:
names = {"Renata", "Marek", "Maciek", "Karolina", "Marcel"}
letter = ['R', 'M', 'A', 'K', 'C']
counter = 0
for letter in names:
print("R =", names.count("R"))
print("M =", names.count("M"))
print("A =", names.count("A"))
print("K =", names.count("K"))
print("C = ", names.count("C"))
I am very new to Python as you can see so I would greatly appreciate some input or help. Please show the changes that you make to the code. Thank you in advance
CodePudding user response:
For example, this way:
names = {"Renata", "Marek", "Maciek", "Karolina", "Marcel"}
names_concatenated = "".join(names).upper()
letters = ['R', 'M', 'A', 'K', 'C']
for letter in letters:
print(f"Letter '{letter} occurrences count in `names`: "
f"{names_concatenated.count(letter)}")
Here we have:
Letter 'R' occurrences count in `names`: 4
Letter 'M' occurrences count in `names`: 3
Letter 'A' occurrences count in `names`: 7
Letter 'K' occurrences count in `names`: 3
Letter 'C' occurrences count in `names`: 2
CodePudding user response:
The Counter
subclass in the inbuilt collections
library is very convenient for this sort of thing. I would implement it like this:
from collections import Counter
names = {"Renata", "Marek", "Maciek", "Karolina", "Marcel"}
all_letters = ''.join(names).upper()
counter = Counter(all_letters)
for l in ['R', 'M', 'A', 'K', 'C']:
print(l, ":", counter[l])
Output:
R : 4
M : 3
A : 7
K : 3
C : 2
CodePudding user response:
Here's one approach:
names = {"Renata", "Marek", "Maciek", "Karolina", "Marcel"}
# Create a dictionary that maps each letter that we're tracking to a frequency counter.
letter_counters = {'R': 0, 'M': 0, 'A': 0, 'K': 0, 'C': 0}
# Go through the set of names, one at a time, and add the frequency of each letter that we're tracking to our counters.
# .upper() is used to make our counting case-insensitive.
for name in names:
for letter in letter_counters:
letter_counters[letter] = name.upper().count(letter)
# Transform the dictionary into a list. (This could be made more concise using a list comprehension, though this is not immediately relevant to the question.)
result = []
for letter in letter_counters:
result.append([letter, letter_counters[letter])