V
V
Vadim_Zaripov2018-09-23 05:43:48
Python
Vadim_Zaripov, 2018-09-23 05:43:48

Python. What is the error in the code (the "frequency analysis" task)?

There is the following task:
Given a text. Print all the words found in the text, one for each line. Words should be sorted in descending order of their number of occurrences in the text, and in case of the same frequency of occurrence - in lexicographic order.
Instruction. Once you've created a dictionary of all words, you'll want to sort it by word frequency. You can achieve what you want by creating a list whose elements are tuples of two elements: the frequency of occurrence of the word and the word itself. For example, [(2, 'hi'), (1, 'what'), (3, 'is')]. Then the standard sort will sort the list of tuples, while the tuples are compared by the first element, and if they are equal, then by the second. This is almost what is required in the task.
Output
Output the answer to the problem.
Examples
input
hi
hi
what is your name
my name is bond
james bond
my name is damme
van damme
claude van damme
jean claude van damme
output
damme
is
name
van
bond
claude
hi
my
james
jean
what
your
passes only 4 out of 22 tests:

d = {}
a = input()
for x in a.splitlines():
    for word in x.split():
        d[word] = d.get(word, 0) + 1 # в словарь добавляется последнее значение суммы
for i in sorted(d.items(), key=lambda x-x[1],x[0])):
    print(i[0])

I suspect it's a typing error. Tell me how to fix?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sashnat, 2018-09-23
@sashnat

The code was copied, apparently, from me, even my comment remained :)))) but
my decision was slightly changed: https://github.com/sashnat/python-codes.-part-5/bl...

A
Andrey Dugin, 2019-10-10
@adugin

from collections import Counter

text = """hi
hi
what is your name
my name is bond
james bond
my name is damme
van damme
claude van damme
jean claude van damme"""

c = Counter(sorted(text.split()))
print(*sorted(c.keys(), key=c.get, reverse=True), sep='\n')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question