A line of lowercase English words separated by single spaces is given. For each distinct word print "word count" on its own line. Print the most frequent words first; when counts are equal, use dictionary order of the words (a first; if one word is the start of another, the shorter comes first).
Input
1 to 1000 words, each 1 to 12 lowercase English letters
Output
one line per distinct word: the word and its count separated by one space
Example 1 · stdin
b a b a c
stdout
a 2
b 2
c 1
main.py
Error List00F8 ↓ · ⇧F8 ↑
Input (stdin)
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
In other languagesShow solutions by language · 8 languages
The trap is the order for equal counts. Sorting by count alone keeps first-appearance order, and in Python sorting (count, word) with reverse=True puts the words from z down. Two keys at once: Python key=lambda kv: (-kv[1], kv[0]), JS b[1] - a[1] || (a[0] < b[0] ? -1 : 1), Java comparingByValue().reversed().thenComparing(comparingByKey()), C# OrderByDescending(...).ThenBy(..., StringComparer.Ordinal), C a qsort comparator with strcmp, C++ std::sort with a lambda. Counting: Python Counter, Java merge(w, 1, Integer::sum), C# GetValueOrDefault, JS a Map rather than {} (counting in a plain object collides with "constructor" from Object.prototype). C has no map, so it searches an array from the start. Craykon counts with Dict() and passes a compare function's name, Keys.Sort(MostFirst) (like C#'s Sort(Comparison): negative if the first goes first, positive if the second does).
Pythonmain.py · 5 lines
from collections import Countercounts = Counter(input().split())for word, count in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])): print(word, count)
JavaScriptmain.js · 5 lines
const words = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);const counts = new Map();for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);const entries = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));console.log(entries.map(([w, c]) => `${w} ${c}`).join("\n"));
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Map<String, Integer> counts = new HashMap<>(); for (String w : in.readLine().trim().split("\\s+")) counts.merge(w, 1, Integer::sum); List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet()); entries.sort(Map.Entry.<String, Integer>comparingByValue().reversed() .thenComparing(Map.Entry.comparingByKey())); StringBuilder out = new StringBuilder(); for (Map.Entry<String, Integer> e : entries) out.append(e.getKey()).append(' ').append(e.getValue()).append('\n'); System.out.print(out); }}
C#Main.cs · 15 lines
using System;using System.Collections.Generic;using System.Linq;class Program{ static void Main() { var counts = new Dictionary<string, int>(); foreach (string w in Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries)) counts[w] = counts.GetValueOrDefault(w) + 1; var sorted = counts.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key, StringComparer.Ordinal); foreach (var kv in sorted) Console.WriteLine($"{kv.Key} {kv.Value}"); }}