Skip to content

Instantly share code, notes, and snippets.

@darkryder
Last active August 29, 2015 14:15
Show Gist options
  • Save darkryder/cd6d1314a081fd446ec0 to your computer and use it in GitHub Desktop.
Save darkryder/cd6d1314a081fd446ec0 to your computer and use it in GitHub Desktop.
Test records
import datetime
import os
class Checker(object):
""" Holder class for all checking/parsing
"""
@staticmethod
def try_int(number):
try:
return int(number)
except ValueError:
return None
@staticmethod
def is_valid_date(date):
# try:
# d,m,y = date.split('/')
# except ValueError:
# return None
# if any(map(lambda _: try_int(_) is not None), [d,m,y]):
# return None
# decided to use inbuilt function as it does all the work of checking the date
try:
return datetime.datetime.strptime(date, "%m/%d/%Y").strftime("%m/%d/%Y")
except ValueError:
return None
class Worker(object):
def __init__(self):
self.student_ids = set() # stores all the student ids to prevent duplication. set for O(1) lookup
# creates file first if it does not exist
if not os.path.exists('records.txt'):
open('records.txt', 'w').close()
# saving all the ids of all students which were added in the previous sessions
self.records_file = open('records.txt', 'r')
for x in self.records_file.read().split('\n'):
x = x.strip()
if x == '': continue
self.student_ids.add(int(x.split(', ')[0]))
self.records_file.close()
self.records_file = open('records.txt', 'a')
# class private method so that it can't be used publicly
def _add_to_file(self, *args):
prepared_line = ", ".join(map(str, args))
self.records_file.write(prepared_line)
self.records_file.write("\n")
print "Added info to file: %s" % prepared_line
# ensures that input is not an empty string
def get_complete_string(self, what_to_ask):
while True:
print "Enter the %s: " % (what_to_ask,),
temp = raw_input().strip()
if temp == '':
print "The field '%s' can't be left empty!" % what_to_ask.upper()
else: return temp
def add_student(self):
while True:
s_id = self.get_complete_string('student ID')
s_id = Checker.try_int(s_id)
if s_id is not None and s_id > 0:
if s_id not in self.student_ids:
self.student_ids.add(s_id)
break
else: print "A student with this ID already exists"
else: print "The student ID should be a natural number"
# going to allow s_fname, s_lname, s_course to have numbers in
# their values as I'm not sure whether I should allow or not
s_fname = self.get_complete_string("first name")
s_lname = self.get_complete_string("last name")
s_course = self.get_complete_string("course")
while True:
s_date = self.get_complete_string("date of completion")
if Checker.is_valid_date(s_date) is not None: break
print "Date of completion format is invalid. Please enter date in MM/DD/YYYY format."
self._add_to_file(s_id, s_fname, s_lname, s_course, s_date)
def _exit(self):
print "\nExiting gracefully."
print "Have a great ANRC day!"
self.records_file.close()
exit()
def work(self):
print """
ANRC Student Record Taker.
Hello!"""
command_handlers = {'ADD': self.add_student, 'QUIT': self._exit}
while True:
print "\nPlease select whether you want to <ADD> a record or <QUIT>: ",
_ = raw_input().strip().upper()
handler = command_handlers.get(_, None)
if handler is None:
print "Invalid option: %s." % _
continue
if callable(handler):
handler()
else: raise ValueError("The programmer messed up somehow!")
def main():
# try:
worker = Worker()
worker.work()
# except Exception as e:
# print "An unhandled exception was raised: %s", e
if __name__ == '__main__':
main()
1003, Nathan, Swaim, Python Programming, 11/19/2010
1023, Joe, Black, Java Programming, 03/05/2009
1007, Chris, Farley, Basic Malware Analysis, 06/27/2008
1003, Nathan, Swaim, O/S Fundamentals, 04/28/2007
2015, Sambhav, Satija, Python Programming, 03/29/1995
import os
def try_int(number):
try:
return int(number)
except ValueError:
return None
class Record(object):
def __init__(self, _id, fname, lname, course, date):
self.s_id = int(_id.strip())
self.fname = fname.strip()
self.lname = lname.strip()
self.course = course.strip()
self.date = date.strip()
# so that I simply have to write print student
def __str__(self):
return """
Student ID: %(id)s
name : %(name)s
course: %(course)s
date of completion: %(date)s
""" % {'id': self.s_id, 'name': " ".join([self.fname, self.lname]),
'course': self.course, 'date': self.date}
class Worker(object):
def __init__(self):
self.students = [] # stores all the students
if not os.path.exists('records.txt'):
print "'records.txt' does not exist"
exit()
self.records_file = open('records.txt', 'r')
for x in self.records_file.read().split('\n'):
x = x.strip()
if x == '': continue
self.students.append(Record(*x.split(', '))) # will work because of tuple/list unpacking
self.records_file.close()
def list_all_students(self):
print "Listing all %d students." % len(self.students)
for _ in self.students: print _
def get_student_by_id(self):
while True:
print "Enter ID of student: ",
_id = try_int(raw_input().strip())
if _id is not None and _id > 0: break
print "Please enter a natural number as an ID"
results = [_ for _ in self.students if _.s_id == _id]
if not any(results) or len(results) == 0:
print "No student exists with ID: %d." % _id
return
print results[0]
def get_students_by_courses(self):
while True:
print "Enter course name: ",
course = raw_input().strip().lower()
if course != '': break
print "Please enter a course name to search for."
results = [_ for _ in self.students if _.course.lower() == course]
if len(results) == 0:
print "No student records found with course matching '%s'." % course
return
for _ in results: print _
def work(self):
print """
ANRC Student Records Reader.
Hello!"""
command_handlers = {'1': self.list_all_students,
'2': self.get_student_by_id,
'3': self.get_students_by_courses,
'4': self._exit}
while True:
print """
1. List all student records in the records records_file
2. Display record for a specific student ID. Only the first matching is shown
3. Display all records for a specific completed course
4. Exit the system
Option:""",
_ = raw_input().strip().upper()
handler = command_handlers.get(_, None)
if handler is None:
print "Invalid option: %s." % _
continue
if callable(handler):
handler()
else: raise ValueError("The programmer messed up somehow!")
def _exit(self):
print "Have a great ANRC day!"
exit()
def main():
worker = Worker()
worker.work()
if __name__ == '__main__': main()
@darkryder
Copy link
Author

Ensure to keep a trailing new line in the seed_records.txt while copying.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment