I am wanting to make a count of items in the dictionary. When a user enters a value to search, it finds the value's key, then returns the next key before it. i.e.({john:fred, fred: bill})
if the user enters john, it will return bill and vice versa.
My code is:
myDict = {}
with open("names.dat") as f:
for line in f:
for pair in line.strip ().split(', '):
i = 0
x = 0
(key, val) = pair.split (":")
myDict[key.strip(":")] = val
print "father: ", key , " son: ", val
def findFather (myDict, lookUp):
father = ""
for key, val in myDict.iteritems( ):
if val == lookUp:
key = key
father = key
return father
lookUp = raw_input ("Enter a son's name: ")
print findFather(myDict, lookUp)
the dictionary values are:
john:fred, fred:bill, sam:tony, jim:william, william:mark, krager:holdyn, danny:brett, danny:issak, danny:jack, blasen:zade, david:dieter, adam:seth, seth:enos
According to your comments, you're trying to find the grandfather of a person in a database mapping people to their fathers:
def read_db(fname):
with open(fname) as f:
return dict(pair.split(":")
for pair in line.strip().split(", ")
for line in f)
def grandfather(db, person):
return db.get(db.get(person)) # same as db[db[person]] except returns None when no match found instead of error
def main():
DB = read_db("names.dat")
print "\n".join("father: %s son: %s" % pair for pair in DB)
person = raw_input("Enter a son's name: ")
print grandfather(DB, person) # prints None if no father or no grandfather found
main()
As you can see, DB is the only needed variable in the entire program (person in main can also be inlined); in your question, your code contains a lot of noise that does absolutely nothing preventing you from understanding your code and making your question look very untidy. So try to clean everything up next time you ask a question on Stack Overflow. Also, check out the almighty PEP8!
Related
Hard to explain this in a simple subject. This is with a GET, no POSTs.
I have a function defined in a different file, we'll say list_gen.py that returns list 'gen_list'. 'gen_list' is a global variable here.
In the views.py, I call this function and assign the output as 'output_list' and send it with the return as such: " return render(request, 'detail.html', {'output_list':output_list}.
Then, in detail.html I simply place the results with {{output_list}}.
When I visit the page, I see the exact output I expected. But, if press refresh, the output duplicates and continues to do so each time I press refresh or if I visit another entry that uses that detail.html page.
Has anyone seen this before?
Below is the view in question. The suspect list is "ped"
#login_required(login_url='/accessdenied/')
def detail(request, did):
try:
dog = Dogs.objects.get(did__exact=did)
resp = pedigree(did, 3)
ped = ''.join(map(str, resp))
try:
dam = Dogs.objects.get(did__exact=dog.dam).registered_name
except:
dam = "Not Listed"
try:
sire = Dogs.objects.get(did__exact=dog.sire).registered_name
except:
sire = "Not Listed"
parents = {'dam': dam, 'sire': sire}
except Dogs.DoesNotExist:
raise Http404("Dog does not exist")
return render(request, 'main/detail.html', {'dog': dog, 'parents': parents, 'ped': ped})
Below am image of the first time visiting the details for a specific entry (a dog):
And refresh a few times, and then visit a different entry. Note that each recent entry appears at the bottom.
The pedigree function (which calls printTree). Yes... I am making an html file into a list which is probably dumb. BUT, I get the exact same duplication if I use the "dog" list you see commented out where used.
dog = []
ped = ['<table border=1>']
def pedigree(did, max):
'''
:param did: id of the child dog
:param max: max number of generations to display
:return: list of dogs
'''
con = sqlite3.connect(f)
con.row_factory
cursor = con.execute('SELECT "Registered Name", ROUND(((JulianDay("now") - JulianDay("Date of Birth"))/365.25),1), "Sex" FROM dogs where did IS %s ' % did).fetchall()
for row in cursor:
name, age, gender = row[0], row[1], row[2]
sql = "SELECT a.Sire, a.Dam, s.'Registered Name', d.'Registered Name' FROM dogs a INNER JOIN dogs s ON a.Sire = s.did INNER JOIN dogs d ON a.Dam = d.did WHERE a.did = "
printTree(sql, did, name, 0, max)
return ped
#return dog
def printTree(stmt, did, name, N, max):
'''
:param stmt: sql statement to query information
:param did: dog to obtain information on
'''
rspan = 2**(max-N)
if (rspan > 1):
ped.append('<td rowspan='+str(rspan)+'><a href=/dogs/'+str(did)+'>'+name+'</td>')
# dog.append({'name': name, 'rspan': rspan})
else:
ped.append('<td><a href=/dogs/'+str(did)+'>'+name+"</td>")
if (N == max):
ped.append("</tr><tr>")
if(N < max):
s = None
d = None
sn = None
dn = None
con = sqlite3.connect(f).execute(stmt+str(did)).fetchall()
for row in con:
s, d, sn, dn = row[0], row[1], row[2], row[3]
if (s and sn) != None:
printTree(stmt, s, sn, N+1, max)
if (d and dn) != None:
printTree(stmt, d, dn, N+1, max)
Thanks to the comments, I fixed by altering the pedigree function as such to clear the list.
ped = []
def pedigree(did, max):
'''
:param did: id of the child dog
:param max: max number of generations to display
:return: list of dogs
'''
ped.clear()
ped.append('<table border=1>')
con = sqlite3.connect(f)
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")
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)
I'm trying to implement a function to find occurrences in a list, here's my code:
def all_numbers():
num_list = []
c.execute("SELECT * FROM myTable")
for row in c:
num_list.append(row[1])
return num_list
def compare_results():
look_up_num = raw_input("Lucky number: ")
occurrences = [i for i, x in enumerate(all_numbers()) if x == look_up_num]
return occurrences
I keep getting an empty list instead of the ocurrences even when I enter a number that is on the mentioned list.
Your code does the following:
It fetches everything from the database. Each row is a sequence.
Then, it takes all these results and adds them to a list.
It returns this list.
Next, your code goes through each item list (remember, its a sequence, like a tuple) and fetches the item and its index (this is what enumerate does).
Next, you attempt to compare the sequence with a string, and if it matches, return it as part of a list.
At #5, the script fails because you are comparing a tuple to a string. Here is a simplified example of what you are doing:
>>> def all_numbers():
... return [(1,5), (2,6)]
...
>>> lucky_number = 5
>>> for i, x in enumerate(all_numbers()):
... print('{} {}'.format(i, x))
... if x == lucky_number:
... print 'Found it!'
...
0 (1, 5)
1 (2, 6)
As you can see, at each loop, your x is the tuple, and it will never equal 5; even though actually the row exists.
You can have the database do your dirty work for you, by returning only the number of rows that match your lucky number:
def get_number_count(lucky_number):
""" Returns the number of times the lucky_number
appears in the database """
c.execute('SELECT COUNT(*) FROM myTable WHERE number_column = %s', (lucky_number,))
result = c.fetchone()
return result[0]
def get_input_number():
""" Get the number to be searched in the database """
lookup_num = raw_input('Lucky number: ')
return get_number_count(lookup_num)
raw_input is returning a string. Try converting it to a number.
occurrences = [i for i, x in enumerate(all_numbers()) if x == int(look_up_num)]
This is supposed to import into a dictionary a key and a value (i.e. john: fred, etc..) from a .dat file. When the program is run, it is supposed to ask the user to enter the son's name (value in the dictionary) and return the key associated with it.
For example, if the user entered fred, it should return john
But the problem is when it is called, it prints "none" instead of the key. Any one that can help is very appreciated.
dataFile = open("names.dat", 'r')
myDict = { }
for line in dataFile:
for pair in line.strip(). split(","):
k,v = pair. split(":")
myDict[k.strip (":")] = v.strip()
print(k, v)
dataFile.close()
def findFather(myDict, lookUp):
for k, v in myDict.items ( ):
for v in v:
if lookUp in v:
key = key[v]
return key
lookUp = raw_input ("Enter a son's name: ")
print "The father you are looking for is ", findFather(myDict, lookUp)
the file is
john:fred, fred:bill, sam:tony, jim:william, william:mark, krager:holdyn, danny:brett, danny:issak, danny:jack, blasen:zade, david:dieter, adam:seth, seth:enos
the problem is
(' seth', 'enos')
Enter a son's name: fred
The father you are looking for is None
I would suggest simply mapping the dictionary the other way so you can use it normally (accessing by key, not by value). After all, dicts map keys to values, not the other way around:
>>> # Open "names.dat" for reading and call it namefile
>>> with open('names.dat', 'r') as namefile:
... # read file contents to string and split on "comma space" as delimiter
... name_pairs = namefile.read().split(', ')
... # name_pairs is now a list like ['john:fred', 'fred:bill', 'sam:tony', ...]
>>> # file is automatically closed when we leave with statement
>>> fathers = {}
>>> for pair in name_pairs: # for each pair like 'john:fred'
... # split on colon, stripping any '\n' from the file from the right side
... father, son = [name.rstrip('\n') for name in pair.split(':')]
... # If pair = 'john:fred', now father is 'john' and son is 'fred'
... fathers[son] = father # which we enter into a dict named fathers
...
>>> fathers['fred'] # now fathers['father_name'] maps to value 'son_name'
'john'