HW3E - Editorial

PROBLEM LINK:
Practice
source

Author: SQU_Test

DIFFICULTY:
Easy

PREREQUISITES:
Pairs of Strings, Matching.

PROBLEM:
You have a new instructor of COMP4204 and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.

You know two languages, and the instructor is giving the lecture in the first one. The words in both languages consist of lowercase English characters; each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.

You can write down every word the instructor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.

You are given the text of the lecture the instructor is going to read. Find out how the lecture will be recorded in your notes.

EXPLANATION:
In this task you must find for every string in the text the pair containing that string, and from two strings of that pair output the shortest one.

TIME COMPLEXITY:
Time complexity of the solution is O(n).

SOLUTIONS:

Setter’s Solution
    n,m = map(int,input().split())
    f1 = {}

    for i in range(m):
        x,y = input().split()
        f1[x.strip()] = y.strip() 
 

    line = input().split()
    res = ""
    for i in range(len(line)):
        line[i] = line[i].strip()
        if len(f1[line[i]]) < len(line[i]):
            res = res + f1[line[i]] + " "
        else:
            res = res + line[i] + " "

    print(res)