class Course:
def __init__(self, name, classroom, instructor, day, start_time, end_time):
self.name = name
self.classroom = classroom
self.instructor = instructor
self.day = day
self.start_time = start_time
self.end_time = end_time
class Schedule:
def __init__(self):
self.courses = []
program = [["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"]]
def add_course(self, course):
self.courses.append(course)
def print_schedule(self):
days = ["Monday","Tuesday","Wednesday","Thursday","Friday"]
program = [["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"],["9","10","11","12","13","14","15","16","17"]]
for course in self.courses:
for j in range(course.start_time-9,course.end_time-8):
program[days.index(course.day)][j] += f" {course.name} class from {course.instructor} at {course.classroom}"
for i in range(len(days)):
print(days[i],":")
for k in program[i]:
print(k)
schedule = Schedule()
schedule.add_course(Course("Physics","MED A11","James","Monday",9,11))
schedule.add_course(Course("Logic Design","EEB 4105","Jack","Wednesday",9,10))
schedule.add_course(Course("Logic Design","EEB 4205","Jack","Wednesday",15,17))
schedule.print_schedule()
Here I wanted to create an weekly schedule, I want it to write something when two classes collide. So their self.day need to be same and the times need to intersect.
For times I can do something like
time = {for i in range(start_time,end_time+1)}
if time1.intersection(time2) != 0:
#...
But I don't know how to reach 2 different Course elements at the same time. Also would be great if you have any suggestions for this code.
You can add a method to the Course class that checks it against another Course to see if they collide. When you add a course, have it loop through the existing courses to see if it collides with the existing courses in your Schedule.
class Course:
def __init__(self, name, classroom, instructor, day, start_time, end_time):
self.name = name
self.classroom = classroom
self.instructor = instructor
self.day = day
self.start_time = start_time
self.end_time = end_time
def check_collision(self, other):
if self.day == other.day:
if other.start_time < self.start_time < other.end_time:
return True
if other.start_time < self.end_time < other.end_time:
return True
if self.start_time < other.start_time < self.end_time:
return True
if self.start_time < other.end_time < self.end_time:
return True
return False
class Schedule:
def __init__(self):
self.courses = []
self.program = [
["9","10","11","12","13","14","15","16","17"],
["9","10","11","12","13","14","15","16","17"],
["9","10","11","12","13","14","15","16","17"],
["9","10","11","12","13","14","15","16","17"],
["9","10","11","12","13","14","15","16","17"],
]
def add_course(self, course):
for c in self.courses:
if course.check_collision(c):
print(f'New course has collision with course: {c.name} on {c.day}: {c.start_time}-{c.end_time}')
break
else:
self.courses.append(course)
def print_schedule(self):
days = ["Monday","Tuesday","Wednesday","Thursday","Friday"]
program = [x.copy() for x in self.program]
for course in self.courses:
for j in range(course.start_time-9,course.end_time-8):
program[days.index(course.day)][j] += f" {course.name} class from {course.instructor} at {course.classroom}"
for i in range(len(days)):
print(days[i],":")
for k in program[i]:
print(k)
So based on your Code, what you can do is define a compare function for the class Schedule, you make a Schedule object to hold many courses. So if you want to access a course within a Schedule you need to do schedule.courses[i]. But I suggest you add the following function to the courses class to solve your problem.
def compare_course(self, other_course):
my_time = {i for i in range(start_time, end_time+1)}
other_time = {i for i in range(other_course.start_time, other_course.end_time+1)}
if my_time.intersection(other_course.time) != set():
return "Course Collides"
else:
return "Course does not collide"
I am trying to iterate through a class object that contains 2 class objects within it and find a matching attribute using a for loop, the attribute here is "title" that has the value = "hello there", so asking for an input title then try to match it with a title within the 2 class objects , when i enter the correct title, i still get the error that says "Error: Please enter a valid book title" ..
import random
books = []
def random_title():
title = 'hello there'
return title
class Books:
def __init__(self, title =''):
self.title = title
def set_title(self, title = '' ):
self.title = random_title()
def get_title(self):
return self.title
def __getitem__(self, title):
return self.title
class BookList(Books):
def __init__(self):
self.book_list = []
def store_book(self, book):
self.book_list.append(book)
def search_book(self):
search_method = input()
while True:
if search_method not in ['1']:
search_method = input()
else:
search_method = int(search_method)
if search_method == 1:
book_title = input().title()
while True:
for item in self.book_list:
if book_title != item.title or book_title != "Back":
book_title = input('Error: Please enter a valid book title or "back" to go back to the main menu: ').title()
else:
if book_title == 'Back':
main()
else:
if book_title == item.title:
print(item)
def __getitem__(self, index):
return self.book_list[index]
def main():
book1 = Books()
book1.set_title()
book2 = Books()
book2.set_title()
book_list = BookList()
book_list.store_book(book1)
book_list.store_book(book2)
book_list.search_book()
main()
This code does what you were trying to do. I suggest you compare this to your own code to see where you went awry.
books = []
class Books:
def __init__(self, title =''):
self.title = title
def set_title(self, title = '' ):
self.title = title
def get_title(self):
return self.title
class BookList(Books):
def __init__(self):
self.book_list = []
def store_book(self, book):
self.book_list.append(book)
def search_book(self):
while True:
search_method = int(input('Method? '))
if search_method in [1]:
break
print("try again")
if search_method == 1:
while True:
book_title = input('Title? ')
if book_title == "back":
return False
for item in self.book_list:
if book_title == item.title:
print(item)
break
else:
print('Error: Please enter a valid book title or "back" to go back to the main menu.')
def __getitem__(self, index):
return self.book_list[index]
def main():
book1 = Books('one')
book2 = Books('two')
book_list = BookList()
book_list.store_book(book1)
book_list.store_book(book2)
book_list.search_book()
main()
There are some more significant design problems here. The BookList class should not be doing any I/O. It is a utility class. The mainline code should ask for the search method and the book title, and then call methods in the BookList to do the search and return the found result. Let the main code do any I/O that is needed.
I have a program that simulates a bus in the form of a list and there is an ability to add passengers to the bus. I want to be able to set a max number of passengers, so that if the list exceeds 25 passengers I display a code stating that the bus is full.
Is it possible to set this limit in a list with Python.
Here is a snippet of the code:
#defining a class for the passenger list
class Bus:
passengers = []
number_of_passengers = 0
You can use super keyword for override lists.
class PassengerList(list):
limit = 0
def __init__(self, lim):
self.limit = lim
def append(self, item):
if len(self) >= self.limit:
raise Exception('Limit exceeded.')
super(PassengerList, self).append(item)
passengers = PassengerList(25)
passengers.append('abc')
You can set limit by parameter.
You'd probably want to check the length of the list and then decide if you'll add a passenger or display a message. Something like so:
class Bus:
def __init__(self, max_number_of_passengers = 25):
self.passengers = []
self.max_number_of_passengers = max_number_of_passengers
def add_passenger(self, passenger):
if len(self.passengers) > self.max_number_of_passengers:
# display message
else:
self.passengers.append(passenger)
you can use a class
class Bus:
def __init__(self):
self.passengers = []
self.MAX_LIMIT = 25
def add_passenger(self, passenger):
if(len(self.passengers) <= self.MAX_LIMIT):
self.passengers.append(passenger)
else:
print('sorry bus is full')
def show_passengers(self):
print(self.passengers)
bus = Bus()
for i in range(26):
bus.add_passenger(i)
bus.add_passenger(26) #sorry bus is full
class Bus:
def __init__(self, limit=25):
self.passengers = []
self.bus_limit = limit
self.is_bus_full = False
def add_passenger(self):
if len(self.passengers) < self.bus_limit:
self.passengers.append(1) # add dummy values
else:
self.is_bus_full = True
def passenger_left(self):
self.passengers.pop()
def bus_status(self):
if self.is_bus_full:
return 'This bus is full'
else:
return 'This bus has vacant seats'
You can write something like this.
I am trying to complete a series of class definition tasks and can't seem to get past this one. It is part of a 3 part series; the first part asks you to model a library book, which I could complete easily.
The next part is asking to create a Member class to model a library member and include a borrow_book() and a return_book() method, and to get the member's list of all loan books to print out in alphabetical order.
I cannot understand which part I am going wrong on. Could someone possibly point me in the right direction? I have included my code so far below.
class Book(object):
def __init__(self, title, author, copies=1, loan=0):
self.title = title
self.author = author
self.copies = copies
self.loan = loan
def checkbook(self, title):
for book in self.title:
if book.title in self.title:
return book
else:
print("Sorry, Not Available.")
def borrow_book(self):
abc = self.checkbook(title)
print(abc)
self.loan += 1
self.copies -= 1
def return_book(self):
self.loan -= 1
def __str__(self):
r = []
r.append('Title: {}'.format(self.title))
r.append('Author: {}'.format(self.author))
r.append('Copies: {}'.format(self.copies))
r.append('On loan: {}'.format(self.loan))
return '\n'.join(r)
def sort_books(b):
return b.title
class Member(object):
def __init__(self, mid, name, loans=0):
self.mid = mid
self.name = name
self.loans = loans
self.d = {}
def __str__(self, mid, name, loans=0):
r = []
r.append('ID: {}'.format(self.mid))
r.append('Name: {}'.format(self.name))
r.append('Loans: {}'.format(self.loans))
l = ['{}'.format(b) for b in sorted(self.d.values(), key=sort_books)]
return '\n'.join(r)
return '\n'.join(l)
class Trip(object):
'a class that abstracts a trip to a destination'
def __init__(self, destination='Nowhere', items=[] ):
'Initialize the Trip class'
self.destination = destination
self.items = items
class DayTrip(Trip):
'a class that abstracts a trip to a destination on a specific day'
def __init__(self, destination='Nowhere', items=[] , day='1/1/2019' ):
'Initialize the Trip class'
self.destination = destination
self.items = items
self.day = day
class ExtendedTrip(Trip):
'a class that abstracts a trip to a destination on between two dates'
def __init__(self, destination='Nowhere', items=[] , day='1/1/2019' ,
endDay = '12/31/2019' ):
'Initialize the ExtendedTrip class'
self.destination = destination
self.items = items
self.day = day
self.endDay = endDay
def luggage(lst):
I want luggage to take all of the items from each class and print a list printed of all thew unique items.
these are some example inputs:
trip1 = Trip('Basement', ['coat','pants','teddy bear'])
trip2 = DayTrip('Springfield',['floss', 'coat','belt'], '2/1/2018')
trip3 = ExtendedTrip('Mars',['shampoo', 'coat','belt'], '4/1/2058')
trip4 = ExtendedTrip()
Each trip is appended to a list and then it will take a set of the list of items which prints this:
{'pants', 'belt', 'toothbrush', 'floss', 'shampoo', 'teddy bear', 'coat'}
Try something like the following (untested).
def luggage(lst):
items = set()
for trip in lst:
for item in trip.items:
items.add(item)
return items