{ }codelper
map lookupkey existsP0063

Phone book lookup

The first line gives n, the number of people in the phone book.
Each of the next n lines gives "name number" separated by one space.
The next line gives the number of queries q, followed by q lines each holding a name to look up.
For each query print that name's number on its own line, or "unknown" if the name is not in the phone book.

Input
1 ≤ n ≤ 1000, 1 ≤ q ≤ 1000.
Names are 1 to 12 lowercase English letters and are distinct within the phone book.
A number is 1 to 20 characters of digits and '-' (no spaces).
Queried names are also 1 to 12 lowercase English letters
Output
q lines, each a number or "unknown"
Example 1 · stdin
3
kim 010-1234-5678
lee 02-555-0101
park 031-777-8888
3
lee
choi
kim
stdout
02-555-0101
unknown
010-1234-5678
main.py
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 looking up a name that is not there, and each language reacts differently: Python book[name] stops with KeyError (use book.get(name, "unknown")), C# book[name] throws KeyNotFoundException (use TryGetValue), and Java get quietly returns null, which prints as "null" (use getOrDefault).
In JS a plain object {} gives undefined, and worse, "constructor" in book is true, so you get a function from Object.prototype: use a Map with has/get.
C++ book[name] inserts an empty value when the key is missing, so ask with find.
C has no map: qsort by name, then bsearch.
Craykon asks first with book.Contains(name) on a Dict() (reading a missing key stops the program, like Python).

Pythonmain.py · 11 lines
import sys lines = sys.stdin.read().split("\n")n = int(lines[0])book = {}for line in lines[1:n + 1]:    name, number = line.split()    book[name] = numberq = int(lines[n + 1])for name in lines[n + 2:n + 2 + q]:    print(book.get(name, "unknown"))
JavaScriptmain.js · 14 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const book = new Map();for (let i = 1; i <= n; i++) {  const [name, number] = lines[i].split(" ");  book.set(name, number);}const q = Number(lines[n + 1]);const out = [];for (let i = 0; i < q; i++) {  const name = lines[n + 2 + i].trim();  out.push(book.has(name) ? book.get(name) : "unknown");}console.log(out.join("\n"));
TypeScriptmain.ts · 15 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const book = new Map<string, string>();for (let i = 1; i <= n; i++) {  const [name, number] = lines[i].split(" ");  book.set(name, number);}const q: number = Number(lines[n + 1]);const out: string[] = [];for (let i = 0; i < q; i++) {  const name: string = lines[n + 2 + i].trim();  out.push(book.get(name) ?? "unknown");}console.log(out.join("\n"));
JavaMain.java · 24 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        Map<String, String> book = new HashMap<>();        for (int i = 0; i < n; i++) {            String[] parts = in.readLine().trim().split(" ");            book.put(parts[0], parts[1]);        }        int q = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        for (int i = 0; i < q; i++) {            String name = in.readLine().trim();            out.append(book.getOrDefault(name, "unknown")).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 22 lines
using System;using System.Collections.Generic; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        var book = new Dictionary<string, string>();        for (int i = 0; i < n; i++)        {            string[] parts = Console.ReadLine().Split(' ');            book[parts[0]] = parts[1];        }        int q = int.Parse(Console.ReadLine());        for (int i = 0; i < q; i++)        {            string name = Console.ReadLine().Trim();            Console.WriteLine(book.TryGetValue(name, out string number) ? number : "unknown");        }    }}
C++main.cpp · 21 lines
#include <iostream>#include <string>#include <unordered_map> int main() {    int n, q;    std::cin >> n;    std::unordered_map<std::string, std::string> book;    for (int i = 0; i < n; i++) {        std::string name, number;        std::cin >> name >> number;        book[name] = number;    }    std::cin >> q;    for (int i = 0; i < q; i++) {        std::string name;        std::cin >> name;        auto it = book.find(name);        std::cout << (it != book.end() ? it->second : "unknown") << '\n';    }}
Cmain.c · 31 lines
#include <stdio.h>#include <stdlib.h>#include <string.h> struct Entry {    char name[13];    char number[32];}; static int by_name(const void *pa, const void *pb) {    const struct Entry *a = pa, *b = pb;    return strcmp(a->name, b->name);} int main(void) {    static struct Entry book[1000];    int n, q;    scanf("%d", &n);    for (int i = 0; i < n; i++) scanf("%12s %31s", book[i].name, book[i].number);    /* C에는 사전이 없다: 이름 순으로 정렬해 두고 bsearch로 찾는다 */    qsort(book, n, sizeof book[0], by_name);    scanf("%d", &q);    for (int i = 0; i < q; i++) {        struct Entry key;        scanf("%12s", key.name);        struct Entry *found = bsearch(&key, book, n, sizeof book[0], by_name);        if (found) puts(found->number);        else puts("unknown");    }    return 0;}
Craykonmain.cray · 20 lines
n = Console.ReadLine().ToNumber();book = Dict();for (i = 0; i < n; i++){    parts = Console.ReadLine().Split();    book[parts[0]] = parts[1];}q = Console.ReadLine().ToNumber();for (i = 0; i < q; i++){    name = Console.ReadLine().Trim();    if (book.Contains(name))    {        Console.WriteLine(book[name]);    }    else    {        Console.WriteLine("unknown");    }}