hackerrank day 8 python - python-2.7

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?

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.

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

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.

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')

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")

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()

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

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

# 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

#Using Setter and Getter
n = int(input())
d = {}
while n:
x, y = input().split()
d.setdefault(x,y)
n -= 1
while True:
try:
inp = input()
if d.get(inp):
print(f"{inp}={d.get(inp)}")
else:
print(f"Not found")
except EOFError:
break

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")

Related

I'm very new to python and don't know how to put a dataset into two different lists

So I am given a dataset(student number, first name, last name, date of birth, study program) and with this I have to create a program that processes this data and puts them in one of two lists: valid data and corrupted data. Sometimes data values are corrupted and the program must report corrupted values. Any invalid or empty value is defined as corrupted.
Student number has this format: 7 digits, starting with 0 and second digit (from left) can be either 9 or 8. Example: 0212345 is not valid
First name and last names, contains only alphabet.
Date of birth has this format: YYYY-MM-DD. Days between 1 and 31, months between 1 and 12 and Years between 1960 and 2004.
Study program can have one of these values: INF, TINF, CMD, AI.
I also have a csv file with the dataset which looks like this:
0893527,Ruggiero,Fifield,1976-08-18,DS
0944991,Vanny,Jerromes,1996-08-10,TINF
0959490,Abbe,Trees,1986-11-29,DS
This obviously is not the entire list, but the rest looks exactly the same.
I really need help with this since I'm getting nowhere. Any help and/or tips are appreciated
This is the code that I already have made:
import os
import sys
valid_lines = []
corrupt_lines = []
def validate_data(line):
pass
def main(csv_file):
with open(os.path.join(sys.path[0], csv_file), newline='').readlines() as csv_file:
next(csv_file)
for line in csv_file:
validate_data(line.strip())
for digits in csv_file:
if csv_file[1] != (8,9):
print('')
print('### VALID LINES ###')
print("\n".join(valid_lines))
print('### CORRUPT LINES ###')
print("\n".join(corrupt_lines))
if __name__ == "__main__":
main('students.csv')
You can try to use re module to validate number, names. For a date you can use str.split. For a valid program you can use set:
import re
import csv
valid, corrupted = [], []
pat_number = re.compile(r"^0[89]\d{5}$")
pat_names = re.compile(r"^[a-zA-Z]+$")
valid_programs = {"INF", "TINF", "CMD", "AI"}
with open("your_data.csv", "r") as f_in:
reader = csv.reader(f_in)
for row in reader:
number, first_name, last_name, date, program = row
match = pat_number.search(number)
if not match:
print(f"{number=} invalid")
corrupted.append(row)
continue
match = pat_names.search(first_name)
if not match:
print(f"{first_name=} invalid")
corrupted.append(row)
continue
match = pat_names.search(last_name)
if not match:
print(f"{last_name=} invalid")
corrupted.append(row)
continue
try:
y, m, d = map(int, date.split("-"))
if y < 1960 or y > 2004:
print(f"{y=} invalid")
corrupted.append(row)
continue
if m < 1 or m > 12:
print(f"{m=} invalid")
corrupted.append(row)
continue
if d < 1 or d > 31:
print(f"{d=} invalid")
corrupted.append(row)
continue
except:
print(f"{date=} invalid")
corrupted.append(row)
continue
if program not in valid_programs:
print(f"{program=} invalid")
corrupted.append(row)
continue
valid.append(row)
print(f"{valid=}")
print("-" * 80)
print(f"{corrupted=}")
Prints:
program='DS' invalid
program='DS' invalid
valid=[['0944991', 'Vanny', 'Jerromes', '1996-08-10', 'TINF']]
--------------------------------------------------------------------------------
corrupted=[['0893527', 'Ruggiero', 'Fifield', '1976-08-18', 'DS'], ['0959490', 'Abbe', 'Trees', '1986-11-29', 'DS']]

Iterating through a .txt file in an odd way

What I am trying to do is write a program that opens a .txt file with movie reviews where the rating is a number from 0-4 followed by a short review of the movie. The program then prompts the user to open a second text file with words that will be matched against the reviews and given a number value based on the review.
For example, with these two sample reviews how they would appear in the .txt file:
4 A comedy-drama of nearly epic proportions rooted in a sincere performance by the title character undergoing midlife crisis . 2 Massoud 's story is an epic , but also a tragedy , the record of a tenacious , humane fighter who was also the prisoner -LRB- and ultimately the victim -RRB- of history .
So, if I were looking for the word "epic", it would increment the count for that word by 2 (which I already have figured out) since it appears twice, and then append the values 4 and 2 to a list of ratings for that word.
How do I append those ints to a list or dictionary related to that word? Keep in mind that I need to create a new list or dicitonary key for every word in a list of words.
Please and thank you. And sorry if this was poorly worded, programming isn't my forte.
All of my code:
def menu_validate(prompt, min_val, max_val):
""" produces a prompt, gets input, validates the input and returns a value. """
while True:
try:
menu = int(input(prompt))
if menu >= min_val and menu <= max_val:
return menu
break
elif menu.lower == "quit" or menu.lower == "q":
quit()
print("You must enter a number value from {} to {}.".format(min_val, max_val))
except ValueError:
print("You must enter a number value from {} to {}.".format(min_val, max_val))
def open_file(prompt):
""" opens a file """
while True:
try:
file_name = str(input(prompt))
if ".txt" in file_name:
input_file = open(file_name, 'r')
return input_file
else:
input_file = open(file_name+".txt", 'r')
return input_file
except FileNotFoundError:
print("You must enter a valid file name. Make sure the file you would like to open is in this programs root folder.")
def make_list(file):
lst = []
for line in file:
lst2 = line.split(' ')
del lst2[-1]
lst.append(lst2)
return lst
def rating_list(lst):
'''iterates through a list of lists and appends the first value in each list to a second list'''
rating_list = []
for list in lst:
rating_list.append(list[0])
return rating_list
def word_cnt(lst, word : str):
cnt = 0
for list in lst:
for word in list:
cnt += 1
return cnt
def words_list(file):
lst = []
for word in file:
lst.append(word)
return lst
##def sort(words, occurrences, avg_scores, std_dev):
## '''sorts and prints the output'''
## menu = menu_validate("You must choose one of the valid choices of 1, 2, 3, 4 \n Sort Options\n 1. Sort by Avg Ascending\n 2. Sort by Avg Descending\n 3. Sort by Std Deviation Ascending\n 4. Sort by Std Deviation Descending", 1, 4)
## print ("{}{}{}{}\n{}".format("Word", "Occurence", "Avg. Score", "Std. Dev.", "="*51))
## if menu == 1:
## for i in range (len(word_list)):
## print ("{}{}{}{}".format(cnt_list.sorted[i],)
def make_odict(lst1, lst2):
'''makes an ordered dictionary of keys/values from 2 lists of equal length'''
dic = OrderedDict()
for i in range (len(word_list)):
dic[lst2[i]] = lst2[i]
return dic
cnt_list = []
while True:
menu = menu_validate("1. Get sentiment for all words in a file? \nQ. Quit \n", 1, 1)
if menu == True:
ratings_file = open("sample.txt")
ratings_list = make_list(ratings_file)
word_file = open_file("Enter the name of the file with words to score \n")
word_list = words_list(word_file)
for word in word_list:
cnt = word_cnt(ratings_list, word)
cnt_list.append(word_cnt(ratings_list, word))
Sorry, I know it's messy and very incomplete.
I think you mean:
import collections
counts = collections.defaultdict(int)
word = 'epic'
counts[word] += 1
Obviously, you can do more with word than I have, but you aren't showing us any code, so ...
EDIT
Okay, looking at your code, I'd suggest you make the separation between rating and text explicit. Take this:
def make_list(file):
lst = []
for line in file:
lst2 = line.split(' ')
del lst2[-1]
lst.append(lst2)
return lst
And convert it to this:
def parse_ratings(file):
"""
Given a file of lines, each with a numeric rating at the start,
parse the lines into score/text tuples, one per line. Return the
list of parsed tuples.
"""
ratings = []
for line in file:
text = line.strip().split()
if text:
score = text[0]
ratings.append((score,text[1:]))
return ratings
Then you can compute both values together:
def match_reviews(word, ratings):
cnt = 0
scores = []
for score,text in ratings:
n = text.count(word)
if n:
cnt += n
scores.append(score)
return (cnt, scores)

Function List Exercise: List within list not printing

I have been asked to create 3 functions to create Vet Records. I have to use 2 functions to validate the Integer input and String Input respectively. I have completed majority of the code but the final part doesn't get printed when I run the code. My code is as follows:
def getNewVetRecord():
getNewVetRecord=[]
return getNewvetRecord
def getValidInteger():
Ask_for_value = True
while(Ask_for_value == True):
try:
ID = int(input("Pet ID: "))
Ask_for_value = False
except ValueError:
print("Please enter a valid integer")
return ID
def getValidString():
Ask_for_value = False
Input_String = ("")
while(Ask_for_value == False):
Input_String = input("Pet Name: ")
Ask_for_value = Input_String.isalpha()
if(Ask_for_value == False):
print("Please enter a valid name")
return Input_String
def func():
stringValue = getValidString();
integerValue = getValidInteger();
species = input("species:")
ownername = input("owner first name:")
owner_last_name = input("owner last name:")
x=[]
x.append(stringValue)
x.append(integerValue)
x.append(species)
x.append(ownername)
x.append(owner_last_name)
return x
def main():
x=[]
x.append(func())
x.append(func())
x.append(func())
print( 'ID Pet Name Species\tOwner Name' )
print( '-- -------- -------\t----------' )
getVetRecord=[]
for x in getVetRecord:
for ind in x:
print(format(getVetRecord[1][ind], "3d"), format(getVetRecord[2][ind]+"", "11s"), format("", "1s"),\
format(getVetRecord[3][ind]+"", "10s"), format("", "2s"), getVetRecord[5][ind],',', getVetRecord[4][ind])
main()
It is doing the important part correctly, (validation and input) but it is not printing the answer.
It shows the following when I run the code

Appending individual lists created from a list comprehension using values from input()

I created a list comprehension to provide me the following:
listoflists = [[] for i in range(252*5)]
I then simplified the list in variable newlists to contain only the number of lists in range(weeks) which is a dynamic variable.
I want to append each individual list in the following loop for a specified range with the append process moving through each list after its reached a specified length. The values are generated from an input function. For instance, if the first list in newlists exceeds a length of 5 I want the values following the 5th loop to then append to the next list and so on. The code I currently have is:
p = 0
singlist = []
listoflists = [[] for i in range(252*5)]
newlists= [listoflists[i] for i in range(weeks)]
while p<(int(people)*weeks): #fix appending process
for i in range(int(people)*weeks):
weekly =input("Put your hours: ")
singlist.append(int(weekly))
p += 1
if weekly.isalpha() == True:
print("Not a valid amount of time")
for i in range(0,weeks):
while len(newlists[i])<int(people):
newlists[i].append(singlist[i])
This code however appends the same values to all lists in range weeks. What is the most efficient way to fix this? Thank you!
if singlist = [10,15,20,25]
desire output for newlists is: [[10,15],[20,25]]
How I've structured the program:
import sys
import numpy as np
import pandas as pd
from datetime import tzinfo,timedelta,datetime
import matplotlib.pyplot as plt
import itertools as it
from itertools import count,islice
team = []
y = 0
while y == 0:
try:
people = input("How many people are on your engagement? ")
if people.isdigit() == True:
y += 1
except:
print("Not a number try again")
z= 0
while z<int(people):
for i in range(int(people)):
names = input("Name: ")
if names.isalpha() == False:
team.append(names)
z+=1
elif names.isdigit() == True:
print("Not a name try again")
ties = [] # fix looping for more than one person
e = 0
while e<int(people):
for i in range(int(people)):
title = input("What is their title: ")
if title.isdigit() == True:
print("Not a title try again")
else:
ties.append(title)
e+=1
values = [] #fix looping for more than one person
t= 0
while t <int(people):
for i in range(int(people)):
charge = input("How much are you charging for them: ")
if charge.isalpha() == True:
print("Not a valid rate")
else:
values.append(int(charge))
t +=1
weeks = int(input("How many weeks are you including: "))
days = []
x = 0
while x<weeks: #include a parameter for dates of a 7 day difference to only be permitted
try:
for i in range(int(weeks)):
dates = input("Input the dates (mm/dd/yy): ")
dt_start = datetime.strptime(dates,'%m/%d/%y')
days.append(dates)
x+=1
except:
print("Incorrect format")
p = 0
singlist = []
listoflists = [[] for i in range(252*5)]
newlists= [listoflists[i] for i in range(weeks)]
while p<(int(people)*weeks): #fix appending process
for i in range(int(people)*weeks):
weekly =input("Put your hours: ")
singlist.append(int(weekly))
p += 1
if weekly.isalpha() == True:
print("Not a valid amount of time")
def func(items,n):
items = iter(items)
for i in it.count():
out = it.islice(items,weeks*i,weeks*i+n)
if not out:
break
output = list(func(singlist,weeks))
# items = [1,2,3,...n]
# output = [[1,2],[3,4],..], n = 2 elements each
items_ = iter(items)
outiter = iter(lambda: [next(items_) for i in range(n)],[])
outlist = list(outiter)
You can do the same thing using while loop in place of count() and [a:b] slice operation on list instead of islice(). But using iterators is very efficient.

How to avoid duplicate printing of random choiced names from list ( Python)

This program prints duplicate names generated from list please help me get rid of it I added a operator fr it but it's not working
#Subscriber Selector
import random
print "Welcome to Subscriber Picker"
sub_list = ["Ali Abbas","Ansar Abbasi","Hasan Abidi","Saadia Afzaal","Iqbal Ahmad","Iftikhar Ahmad","Khaled Ahmed","Ahmed Tamim","Maulana Mahboob Alam","Malik Barkat Ali"]
def add_list():
input_1 = int(raw_input("How many new users do you want to add? "))
for z in range (0,input_1):
sub_list.append(raw_input ("Enter Name" +" "+ str(z+1) + ":"))
return
add_list()
def generator():
input_2=int(raw_input("How many subscribers to generate? "))
print "-----"
index=0
temp_list = []
ran_name = random.randint(0, len(sub_list)-1)
temp_list.append(sub_list[ran_name])
while len(temp_list) < input_2:
ran_name=random.randint(0,len(sub_list)-1)
temp_list.append(sub_list[ran_name])
if(temp_list[index] == temp_list[index+1]):
temp_list.pop(index)
else:
index = index + 1
for x in temp_list:
print x
print"-----"
return
generator()
Here you go:
temp_list = random.sample( sub_list, input_2 )