2

SPOILER This questions is about the Hackerrank Day 8 challenge, in case you want to try it yourself first.

This is the question they give:

Given n names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each name queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead.

Note: Your phone book should be a Dictionary/Map/HashMap data structure.

The first line contains an integer, n, denoting the number of entries in the phone book. Each of the n subsequent lines describes an entry in the form of 2 space-separated values on a single line. The first value is a friend's name, and the second value is an 8-digit phone number.

After the n lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains name a to look up, and you must continue reading lines until there is no more input.

Note: Names consist of lowercase English alphabetic letters and are first names only.

They go further then to give the input:

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

which expects the output:

sam=99912222
Not found
harry=12299933

I am having trouble with the unknown number of names to query. I tried using a try/except block to stop at an EOFError but I keep timing out on their test cases 1, 2 and 3. It works on two of the other test cases but not those and I assume it must be because I am stuck in a kind of infinite loop using my while True statement? This is what I wrote:

phonebook = {}
entries = int(raw_input())

for n in range(entries):
    name, num = raw_input().strip().split(' ')
    name, num = [str(name), int(num)]
    phonebook[name] = num

while True:
    try:  
        search = str(raw_input())

        if search in phonebook.keys():
            output = ''.join('%s=%r' % (search, phonebook[search]))
            print output
        else:
            print "Not found"
    except EOFError:
        break

I am still fairly new to python so maybe I'm not using the try/except or break methods correctly? I would appreciate if anyone could tell me where I went wrong or what I can do to improve my code?

C. Viljoen
  • 23
  • 1
  • 8
  • Just out of interest: Could you link to the challenge? I'm really interested to solve this myself. :) – MSeifert Jun 12 '17 at 11:31
  • @MSeifert [Hackerrank Day 8](https://www.hackerrank.com/challenges/30-dictionaries-and-maps) If you do get it solved would you mind telling me how please? – C. Viljoen Jun 13 '17 at 12:36

10 Answers10

2

The only mistake you are doing is that you are using

phonebook.keys()

You can loop without using .keys() . It will save time.

phonebook = {}
entries = int(raw_input())

for n in range(entries):
    name, num = raw_input().strip().split(' ')
    name, num = [str(name), int(num)]
    phonebook[name] = num

while True:
    try:  
        search = str(raw_input())

        if search in phonebook:
            output = ''.join('%s=%r' % (search, phonebook[search]))
            print output
        else:
            print "Not found"
    except EOFError:
        break

The above code will work with all the test cases.

Paras jain
  • 362
  • 1
  • 14
1

In python-3

# n, Enter number of record you need to insert in dict
n = int(input())
d = dict()

# enter name and number by separate space
for i in range(0, n):
    name, number = input().split()
    d[name] = number
# print(d)      #print dict, if needed

# enter name in order to get phone number
for i in range(0, n):
    try:
        name = input()
        if name in d:
            print(f"{name}={d[name]}")
        else:
            print("Not found")
    except:
        break

Input:

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

Output:

sam=99912222
Not found
harry=12299933
Biman Pal
  • 111
  • 1
  • 8
  • Hey, can you type an easy explanation of why it worked? – f.khantsis Mar 30 '20 at 09:03
  • 1. 1st for loop will insert data in dictionary, d.2. n, is number of records you need to insert in dictionary. 3. 2nd for loop will search what record you want eg. Sam, harry etc. – Biman Pal Mar 30 '20 at 10:41
0
n = int(input())
d = dict()

for i in range(0, n):
name, number = input().split()
d[name] = number
#print(d) Check if your dictionary  is ready

for i in range(0, n):
    name = input()
    if name in d:
        print(f'{name}={d[name]}')
    else:
        print("Not found")

Try this, It'll work.

0

run this code to pass all the test cases:

n = int(input())
d = {}
for i in range(n):
    tp = input()
    a, b = tp.split()
    d.update({a: b})
inputs = []
input1 = input().strip()
try:
    while len(input1) > 0:
        inputs.append(input1)
        input1 = input().strip()
except:
    pass
for i in inputs:
    if i in d.keys():
        c = 1
        print(i + "=" + d[i])
    else:
        print('Not found')
B. Go
  • 1,404
  • 4
  • 13
  • 21
0

Lets make life easy

Hacker rank 30 Day Code - Day no 8 (@Murtuza Chawala)

n = int(input())
i = 0
book = dict() #Declare a dictionary
while(i < n):
    name , number = input().split() #Split input for name,number
    book[name] = number #Append key,value pair in dictionary
    i+=1
while True: #Run infinitely 
    try:
        #Trick - If there is no more input stop the program
        query = input() 
    except:
        break
    val = book.get(query, 0) #Returns 0 is name not in dictionary
    if val != 0:
        print(query + "=" + book[query])
    else:
        print("Not found")
Community
  • 1
  • 1
Murtaza
  • 1
  • 2
0
n = int(input())
PhoneBook = dict(input().split() for x in range(n))
try:
    for x in range(n):
        key = input()
        if key in PhoneBook: 
            print (key,'=',PhoneBook[key],sep='') 
        else: 
            print('Not found')
except:
        exit()
  • 5
    Although this code might solve the problem, a good answer should also explain **what** the code does and **how** it helps. – BDL Jun 23 '20 at 15:35
0
n= int(input())
dct={}
for i in range(n):
    info=input().split()
    dct[info[0]]=info[1]

while 1:
    try:
        query=input().lower()
        if query in dct:
            print(query+'='+dct[query])
        else:
            print('Not found')
    except EOFError:
        break
0

Below snippet works for me.

noOfTestCases = int(input())
phoneDict = {}

for i in range(noOfTestCases):
    name, phoneNumber = input().split()
    phoneDict[name] = phoneNumber

for i in range(noOfTestCases):
    try:
        name = input()
        if name in phoneDict:
             print(name+'='+phoneDict[name])
        else:
            print("Not found")
    except:
        break
            

Input

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

Output

sam=99912222
Not found
harry=12299933
Shaila B
  • 11
  • 2
0
# Enter your code here. Read input from STDIN. Print output to STDOUT
entries = int( input() )

# print(entries)
data = {}
for i in range(entries):
    # print("i=",i)
    name, num = input().strip().split(" ")
    # print(name)
    # print(num)
    data[name]=num
# print(data)
while True:
    try:
        search = input()
        if search in data.keys():
            print(search,"=",data[search], sep="")
        else:
            print("Not found")
    except EOFError:
        break
 
Input (stdin)
3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

Your Output (stdout)
sam=99912222
Not found
harry=12299933

Expected Output
sam=99912222
Not found
harry=12299933
Veer
  • 1
  • 1
-1
n=int(input())
d=dict()
for i in range(n):
    name,number = input().split()
    d.update({name:number})
for i in range(n):
    name=input()
    if name in d:print(name +"="+d[name])
    else:
        print("Not found")
Andrea Blengino
  • 4,144
  • 22
  • 35
  • 57