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
Related
First project newbie here - In this model I am trying to create a field that combines first and last names of two people depending if the last names are the same or not. If the last name is the same, I want it to display as "first_name1 & first_name2 last_name1". It works except that when last_name1 is empty, which will be the case a lot of the time, it displays something like "John & Jane None". I had to specify last_name1 as a string or else I got an error: must be str, not NoneType. How do I do this properly? Also what do I call this type of function in a model...is it a manager? I wasn't sure how to title this post.
class Contact(models.Model):
first_name1 = models.CharField(max_length=100, verbose_name='First Name', null=True)
last_name1 = models.CharField(max_length=100, verbose_name='Last Name', null=True, blank=True)
first_name2 = models.CharField(max_length=100, verbose_name='First Name (Second Person)', null=True, blank=True)
last_name2 = models.CharField(max_length=100, verbose_name='Last Name (Second Person)', null=True, blank=True)
def get_full_name(self):
combined_name = ''
if self.last_name1 == self.last_name2:
combined_name = self.first_name1 + ' & ' + self.first_name2 + ' ' + str(self.last_name1)
return '%s' % (combined_name)
full_name = property(get_full_name)
The reason on why you're getting an error that last_name1 must be a String, not a NoneType is due to the fact you've set null to True in your field declaration for the said field.
So what's wrong with doing that? When you are defining null=True for fields like CharField or TextField you'll end up having None. The Django convention is to use EMPTY STRING.
Here's a link that talks about how you would use blank or null on field declarations.
You can check if those values are "Truth-y" before doing the comparison check. However, you'll need to decide how to handle the other cases.
#property
def get_full_name(self):
combined_name = ''
if self.last_name1 and self.last_name2:
if self.last_name1 == self.last_name2:
combined_name = self.first_name1 + ' & ' + self.first_name2 + ' ' + str(self.last_name1)
elif self.last_name1: # Only last_name1 is set
pass
elif self.last_name2: # Only last_name2 is set
pass
else: # Both last_name1 and last_name2 are None or ''
pass
return combined_name
The way you've defined the names, any and all of them can be None, if you change them to the empty string you'll have similar problems. To illustrate, lets start by writing a unit test (substitute the empty string for None if you want):
def test_contact_full_name():
# correct.
assert Contact('Jane', None, 'John', None).full_name == "Jane & John"
assert Contact('Bart', 'Simpson', 'Lisa', 'Simpson').full_name == "Bart & Lisa Simpson"
assert Contact('Bart', 'Simpson', 'Frodo', 'Baggins').full_name == "Bart Simpson & Frodo Baggins"
assert Contact('Bart', None, None, None).full_name == "Bart"
assert Contact('Bart', 'Simpson', None, None).full_name == "Bart Simpson"
assert Contact(None, 'Simpson', None, None).full_name == "Simpson"
assert Contact(None, None, None, None).full_name == ""
# correct?
assert Contact('Bart', 'Simpson', 'Lisa', None).full_name == "Bart Simpson & Lisa"
# correct??
assert Contact('Bart', None, 'Lisa', 'Simpson').full_name == "Bart & Lisa Simpson"
Then it's just a question of dividing the problem into smaller pieces, I've put everything into a regular class just to make it easier to test. First some helper methods:
class Contact(object):
def __init__(self, a, b, c, d):
self.first_name1 = a
self.last_name1 = b
self.first_name2 = c
self.last_name2 = d
def combined_last_name(self, a, b):
"Return ``a`` if ``a`` and ``b`` are equal, otherwise returns None."
return a if a and b and a == b else None
def normalize_name(self, n):
"Returns the name or the empty string if ``n`` is None."
return n if n else ""
def get_name(self, f, l):
"""Returns a string containing firstname lastname and omits any of them
if they're None.
"""
if f and l:
return "%s %s" % (f, l)
if f:
return f
elif l:
return l
return ""
def has_second_name(self):
"Returns true if there is a second name."
return self.first_name2 or self.last_name2
then we can define the full_name property:
#property
def full_name(self):
"""Returns a string that combines first and last names of two people
depending if the last names are the same or not. If the last name
is the same, it displays as::
first_name1 & first_name2 last_name1
"""
cln = self.combined_last_name(self.last_name1, self.last_name2)
if cln: # have a common last name..
return "%s & %s %s" % (
self.first_name1,
self.first_name2,
cln
)
elif self.has_second_name():
return "%s & %s" % (
self.get_name(self.first_name1, self.last_name1),
self.get_name(self.first_name2, self.last_name2)
)
else:
return self.get_name(self.first_name1, self.last_name1)
if we put everything in a file named fullname.py we can use the pytest tool (pip install pytest) to run the tests:
c:\srv\tmp> pytest --verbose fullname.py
============================= test session starts =============================
platform win32 -- Python 2.7.16, pytest-3.3.1, py-1.5.2, pluggy-0.6.0 -- c:\srv\venv\finautfaktura\scripts\python.exe
cachedir: .cache
rootdir: c:\srv\tmp, inifile:
plugins: xdist-1.20.1, forked-0.2, django-3.1.2, cov-2.5.1
collected 1 item
fullname.py::test_contact_full_name PASSED [100%]
========================== 1 passed in 0.20 seconds ===========================
All is well... or is it?
Let's write another test:
def test_only_second_name():
assert Contact(None, None, None, "Simpson").full_name == "Simpson"
assert Contact(None, None, "Lisa", "Simpson").full_name == "Lisa Simpson"
assert Contact(None, None, "Lisa", None).full_name == "Lisa"
running pytest again reveals the (first) error:
c:\srv\tmp> pytest --verbose fullname.py
============================= test session starts =============================
platform win32 -- Python 2.7.16, pytest-3.3.1, py-1.5.2, pluggy-0.6.0 -- c:\srv\venv\finautfaktura\scripts\python.exe
cachedir: .cache
rootdir: c:\srv\tmp, inifile:
plugins: xdist-1.20.1, forked-0.2, django-3.1.2, cov-2.5.1
collected 2 items
fullname.py::test_contact_full_name PASSED [ 50%]
fullname.py::test_only_second_name FAILED [100%]
================================== FAILURES ===================================
____________________________ test_only_second_name ____________________________
def test_only_second_name():
> assert Contact(None, None, None, "Simpson").full_name == "Simpson"
E AssertionError: assert ' & Simpson' == 'Simpson'
E - & Simpson
E ? ---
E + Simpson
fullname.py:83: AssertionError
===================== 1 failed, 1 passed in 0.37 seconds ======================
i.e. the property returned " & Simpson" instead of the expected "Simpson" for the first assert.
To fix this we can make the full_name property handle this added complexity as well, or.., we can solve the problem somewhere else, e.g. in the __init__:
class Contact(object):
def __init__(self, a, b, c, d):
self.first_name1 = a
self.last_name1 = b
self.first_name2 = c
self.last_name2 = d
if not a and not b:
# if no name1, then put name2 into name1 and set name2 to None
self.first_name1 = self.first_name2
self.last_name1 = self.last_name2
self.first_name2 = self.last_name2 = None
running pytest again shows that this fixed the second test.
You can of course not provide your own __init__ in a Django model to solve this problem, but you can do something similar in if you override the save(..) method:
def save(self, *args, **kwargs):
if not self.first_name1 and not self.last_name1:
self.first_name1 = self.first_name2
self.last_name1 = self.last_name2
self.first_name2 = self.last_name2 = None
super(Contact, self).save(*args, **kwargs)
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")
I have a test on building a multi-dimension array, doesn't matter it is for expert or rookie usage.
the program should run like this:
Main function: ask user to enter number_of_player
read function: loop and enter name and score of each player and save them into a dict
assign function: check their score, assign their score to a frequency_array to determine their rank and the frequency of players of the same rank.
search function: enable user to search and access data using name, score, location(address of player in dict), rank.
**haven't start working**
display function: print using the search keyword return from search function
**haven't start working**
so my problem comes in, i made all the array, but data doesn't goes in to it, when i print the whole array, it appears to be blank. Please help me, I don't where i got it wrong.
"""
there should be 5 tier ranking syst
there should be no upper boundary for no. of player
"""
def Main():
print "This is a eg of pointer technique(frequency dist) program \n"
Element = 0
score = 0
RecordArray = {}
scoreArray = {}
location=0
scoreArray[Element] = RecordArray
totalfrequencyArray = {}
frequencyArray1 = []
frequencyArray2 = []
frequencyArray3 = []
frequencyArray4 = []
frequencyArray5 = []
while True:
try:
NElement = raw_input("number of player: ")
NElement = int(NElement)
break
except ValueError:
print "Integer only!"
continue
reply = ""
find=""
selection=""
while Element != NElement:
Element += 1
Read(NElement, score, Element)
Assign(NElement, Element, score, location)
print totalfrequencyArray
Search(find, location, selection)
Display(selection, location, reply)
def Read(NElement, score, Element):
Name = raw_input("\n\n\nName: ")
while True:
try:
score = raw_input("Score(1-9K): ")
score = int(score)
if score in range(1, 9001):
break
else:
print "invalid score"
continue
except ValueError:
print "invalid input"
continue
RecordArray={}
scoreArray={}
RecordArray[Name] = score
scoreArray[Element] = RecordArray
return score
return Element
return NElement
"""
promblem encountered :
print function display empty array
"""
def Assign(NElement, Element, score, location):
if score in range(1, 2000):
location = 5
Rank = "Tier 5"
frequencyArray5[Element]
frequencyArray5=frequencyArray5+[Rank]
if Element==NElement:
totalfrequencyArray[location]=frequencyArray5
elif score in range(2001, 4000):
location = 4
Rank = "Bronze"
frequencyArray4[Element]
frequencyArray4=frequencyArray4+[Rank]
if Element==NElement:
totalfrequencyArray[location]=frequencyArray4
elif score in range(4001, 6000):
location = 3
Rank = "Silver"
frequencyArray3[Element]
frequencyArray3=frequencyArray3+[Rank]
if Element==NElement:
totalfrequencyArray[location]=frequencyArray3
elif score in range(6001, 8000):
location = 2
Rank = "Gold"
frequencyArray2[Element]
frequencyArray2=frequencyArray2+[Rank]
if Element==NElement:
totalfrequencyArray[location]=frequencyArray2
elif score in range(8001, 9000):
location = 1
Rank = "Diamond"
frequencyArray1[Element]
frequencyArray1=frequencyArray1+[Rank]
if Element==NElement:
totalfrequencyArray[location]=frequencyArray1
return location
def Display(selection, location, reply):
strformat = '{:<8}{:<20}{}'
if selection == 0:
print (strformat.format("", "scorelist", "ranklist"))
for i, (Element, location) in enumerate(zip(scoreArray, totalfrequencyArray)):
print (strformat.format(i, Element, location))
def Search(find, location, selection):
selection=0
return selection
Main()
I am writing a logger which records the level of the entries.
To make it simple, let's say it logs entries like <level> <message>.
I am now trying to write a log viewer which formats the logfile "nicely" as an indented tree grid.
For example is the raw log file contains:
0 entry1
0 entry2
1 entry3
2 entry4
3 entry5
2 entry6
0 entry7
It should output:
entry1
entry2
└entry3
├entry4
│└entry5
└entry6
entry7
My first steps were
Converting the list into a tree
Recursively print the tree
This worked with one single exception: I cannot figure out how I can pass the information that - referring to the example - before entry5 comes the │ sign to display that the previous level continues after the sub-levels.
So any hint, how to come from the list to the desired output is welcome.
Finally got it:
class LogViewer(LogFile):
"""
Formats raw log file contents nicely
and thus makes it human-readable
"""
__down = False
class EntryTreeNode():
"""
A minimal entry wrapper
"""
def __init__(self, string):
"""
Constructor
"""
lst = string.split(LogEntry.colsep())
if len(lst) != 6:
raise Exception('Invalid entry: ' + string)
else:
self.DATE = datetime.strptime(lst[0], LogEntry.timeformat())
self.ERRLVL = ErrLvlType(lst[1])
self.USER = lst[2]
self.CALLER = lst[3]
self.OFFSET = int(lst[4])
self.MSG = lst[5]
self.tag = self.OFFSET
self.children = []
self.pre = '[' + datetime.strftime(self.DATE, LogEntry.timeformat()) + ']\t' \
+ str(self.ERRLVL) + '\t' \
+ str(self.USER) + '\t'
self.post = str(self.CALLER) + ' \t' + str(self.MSG)
def __repr__(self):
return str(self.tag)
def __init__(self, path):
"""
Constructor
"""
super().__init__(path)
#property
def __sym_last(self):
"""
Returns the symbol for a last entry
"""
return '┌' if self.__down else '└'
#property
def __sym_mid(self):
"""
Returns the symbol for a middle entry
"""
return '├'
#property
def __sym_follow(self):
"""
Returns the symbol for a following entry
"""
return '│'
def __mktree(self, lst):
"""
Converts a log entry list into a tree
"""
roots = []
def children(root, lst):
result = []
while lst:
curr = lst.pop()
if curr.tag == root.tag + 1:
curr.children = children(curr, lst)
result.append(curr)
else:
lst.append(curr)
break
return result
while lst:
curr = lst.pop()
if curr.tag == 0:
curr.children = children(curr, lst)
roots.append(curr)
return roots
def __print_tree(self, root, offset='', prefix='', last=True):
"""
Prints a log entry tree
"""
print(root.pre + offset + prefix + root.post)
if last:
offset += ' '
else:
offset += self.__sym_follow
for i in range(0, len(root.children)):
if i == len(root.children)-1:
prefix = self.__sym_last
last = True
else:
prefix = self.__sym_mid
last = False
self.__print_tree(root.children[i], offset, prefix, last)
def display(self, reverse=False):
"""
Displays the log file nicely
"""
self.__down = reverse
entries = reversed(self.dump()) if reverse else self.dump()
entries = [self.EntryTreeNode(e) for e in entries]
tree = self.__mktree(entries)
for root in tree:
self.__print_tree(root)
I am trying to use web2py to build an app. I have a simple print function that a user submits a key word . The string or int key word is directed to an sqlite db to retrieve a row and output the data. I need to know
1. how to use the print on html.
2. How to split the string...so far i did the list:string
Here is my code:
def first():
form = SQLFORM.factory(Field('visitor_name',
label = 'Please Type Your keyword here!',
requires= [IS_NOT_EMPTY(), IS_LOWER(),'list:string']))
form.element('input[type=submit]')['_onclick'] = "return \
confirm('Are you sure you want to submit:');"
if form.process().accepted:
session.visitor_name = form.vars.visitor_name
redirect(URL('main'))
return dict(form=form)
def main():
while True:
name = request.vars.visitor_name or redirect(URL('first'))
name2 = name[:]
for item in name2:break
name3 = ' '.join(name2)
import sqlite3
id = 0
location = ""
conn = sqlite3.connect("keywords.db")
c = conn.cursor()
c.execute('select * from kmedicals')
records = c.fetchall()
for record in records:
id = record[0]
location = record[15]
if id == name3:
print name3.capitalize(),':' '\n',location
break
sys.exit()
return dict(name=name)
my view...default/main.html:
{{extend 'layout.html'}}
{{=name}}