It's a Python question.

Asked 2 years ago, Updated 2 years ago, 17 views

After the natural number n is entered, n names are entered. Convert the number of times each name is entered into a dictionary form and print it out.

[Input/output example 1]

3
KIM
KIM
KIM
{'KIM': 3}

[Input/output example 2]

5
LEE
LEE
LEE
KIM
PARK
{'LEE': 3, 'KIM': 1, 'PARK': 1}
n=int(input())
user_info={}
c=0
for i in range(n):
    key=input()
    if key in user_info.keys():
        if c>=2:
            c += 1
            user_info[key]=c
            continue
        c=1
        c += 1
        user_info[key]=c
    else:
        c=0
        user_info[key]=c+1
print(user_info)

What's wrong?

python

2022-09-22 08:11

4 Answers

There's a little bit of unnecessary complexity, so I can make it simpler, but the problem seems to work out the way you want it to. How do you get the wrong result?


2022-09-22 08:11


2022-09-22 08:11

It's gonna be a lot simpler.

n=int(input())
user_info={}
for i in range(n):
    key=input()
    if key in user_info.keys():
        user_info[key] = user_info[key] + 1;
    else:
        user_info[key]=1;
print(user_info)

And I think it would be better if you could tell me where the oil comes from from now on...


2022-09-22 08:11

A counter is provided in the primary module.

In [45]: data = [input() for _ in range(int(input()))]                                                     
5
aaa
bbb
aaa
ccc
bbb

In [46]: data                                                                                              
Out[46]: ['aaa', 'bbb', 'aaa', 'ccc', 'bbb']

In [47]: from collections import Counter                                                                   

In [48]: dict(Counter(data))                                                                               
Out[48]: {'aaa': 2, 'bbb': 2, 'ccc': 1}
In [67]: data = [input() for _ in range(int(input()))]                                                     
5
aaa
bbb
aaa
ccc
bbb

In [68]: D = {}                                                                                            

In [69]: for key in data: 
    ...:     ...:     D[key] = D.get(key, 0) + 1 
    ...:                                                                                                   

In [70]: D                                                                                                 
Out[70]: {'aaa': 2, 'bbb': 2, 'ccc': 1}


2022-09-22 08:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.