I am running into a problem and no clue what to do, as I am new to programming. The situation is as follows, we extracted data from a .txt file with names, children etc. and extracted it into a dictionary. The dictionary is accessed with the name as the key, e.g:
# access a single person in allPersons via the name as key
p1 = allPersons['jan']
print("Name:", p1.name)
print("Sex:", p1.sex)
print("Children:")
for p in p1.children:
print(p.name)
with the output being:
Name: jan
Sex: female
Children:
marko
anna15
So far so good, but now I am expected to write a function called count which stores the name so for example ‘stefan’ as the key and the number of occurences as the value for the key, while ignoring numeric suffixes to the name such as ‘stefan02’ or ‘stefan10’ and to be honest I am really lost on this.
def count(persons):
name_counts = {}
# YOUR CODE HERE
raise NotImplementedError()
return name_counts
assert count(allPersons)['stefan'] == 20
I tried messing around with code I found online and imports such as regex but honestly I got even more confused than before and I was hoping I could get some pointers in the right direction. While I’m kinda embarassed to show my code since it is probably wrong, I’m still going to put the miniscule amount I do have on here, to show I have indeed been thinking about the problem myself.
def count(persons):
name_counts = {}
for j in persons:
if j in name_counts:
name_counts[j].name+=1
else:
name_counts[j].name=0
return name_counts
The error I get is ‘nora11’ which is the first name to be fed from the .txt into the dictionary as context.
Thank you in advance!
>Solution :
occu = {}
for p in persons:
for i,k in enumerate(p):
if k.isdigit():
p = p[:i]
if p in occu:
occu[p] += 1
else:
occu[p] = 1
Hope this helps
edit: this doesn’t work if the digits are not at the end of the name, eg
tom --> tom
tom123 --> tom
to123m --> to
123tom -->