Bookshelf classes getting title and genre of book - python

I'm trying to write a code that adds 'fiction' books to a Bookshelf and then prints the names of the 'fiction' books. This is what I have so far.
class Book:
def __init__(self,title,genre):
self.title = title
self.genre = genre
def get_book(self):
return self.title
class Bookshelf:
def __init__(self,title,genre,books):
self.title = title
self.genre = genre
self.books = []
def add_book(self,book):
self.books.append(books)
return True
s1 = Book('Black Roses', 'Fiction')
s2 = Book('Red and Grey', 'Non-fiction')
s3 = Book('Pride and Prejudice','Fiction')
bookshelf = Bookshelf('Fiction')
Any help?

class Book:
def __init__(self,title,genre):
self.title = title
self.genre = genre
def get_book(self):
return self.title
class Bookshelf:
def __init__(self):
self.books = []
def add_book(self,book):
self.books.append(book)
return True
def get_book(self, genre):
res = []
for book in self.books:
if book.genre==genre:
res.append(book.title)
return res
s1 = Book('Black Roses', 'Fiction')
s2 = Book('Red and Grey', 'Non-fiction')
s3 = Book('Pride and Prejudice','Fiction')
z = Bookshelf()
z.add_book(s1)
z.add_book(s2)
z.add_book(s3)
z.get_book('Fiction')
output
['Black Roses', 'Pride and Prejudice']

Since the Bookshelf.__init__ method initializes self.books to an empty list, there's no need for the books parameter.
Since each bookshelf is devoted to a specific genre, you should make sure that books are not put on the wrong shelf.
class Bookshelf:
def __init__(self,title,genre):
self.title = title
self.genre = genre
self.books = []
def add_book(self,book):
if self.genre != book.genre:
raise ValueError(r"Can't put a {book.genre} book on a {self.genre} shelf")
self.books.append(books)
s1 = Book('Black Roses', 'Fiction')
s2 = Book('Red and Grey', 'Non-fiction')
s3 = Book('Pride and Prejudice','Fiction')
f = Bookshelf("Fiction Books", "Fiction")
nf = Bookshelf("Non-Fiction Books", "Non-fiction")
f.add_book(s1)
nf.add_book(s2)
f.add_book(s3)
# Print all fiction books
for book in f.books:
print(book.get_book())

Related

java.lang.IllegalStateException: 2 members with a #ValueRangeProvider annotation must not have the same id (timeslotRangeLS)

Trying to generate school timetable with lab hours.
Kindly help me to solve this error! Thanks in advance.
Here is my code!
#planning_solution
class TimeTable:
timeslot_list: list[Timeslot]
timeslot_list1: list[Timeslot]
room_list: list[Room]
lesson_list: list[Lesson]
lab_list: list[Lab]
score: HardSoftScore
def __init__(self, timeslot_list, timeslot_list1, room_list, lesson_list,lab_list,
score=None):
self.timeslot_list = timeslot_list
self.timeslot_list1 = timeslot_list1
self.room_list = room_list
self.lesson_list = lesson_list
self.lab_list = lab_list
self.score = score
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLS")
def get_timeslot_list(self):
return self.timeslot_list
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLB")
def get_timeslot_list1(self):
return self.timeslot_list1
#problem_fact_collection_property(Room)
#value_range_provider("roomRange")
def get_room_list(self):
return self.room_list
#planning_entity_collection_property(Lesson)
def get_lesson_list(self):
return self.lesson_list
#planning_entity_collection_property(Lab)
def get_lab_list(self):
return self.Lab_list
#planning_score(HardSoftScore)
def get_score(self):
return self.score
def set_score(self, score):
self.score = score
def __str__(self):
return (
f"TimeTable("
f"timeslot_list={format_list(self.timeslot_list)},\n"
f"timeslot_list1={format_list(self.timeslot_list1)},\n"
f"room_list={format_list(self.room_list)},\n"
f"lesson_list={format_list(self.lesson_list)},\n"
f"lab_list={format_list(self.lab_list)},\n"
f"score={str(self.score.toString()) if self.score is not None else 'None'}"
f")"
)
Trying to get the 2 timeslots one for lesson(1 hour) and one for lab(2 hour).Here is my #planning_solution.
I defined 2 #planning_entity for both lab & lesson with #value_range_provider.
#planning_entity
class Lab(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot1: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot1 = None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot1 = timeslot1
self.room = room
#planning_variable(Base, value_range_provider_refs=['roomRange', 'timeslotRangeLB'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLB"])
def get_timeslot1(self):
return self.timeslot1
#value_range_provider(range_id = "timeslotRangeLB", value_range_type = Timeslot)
def get_possible_timeslot_list1(self):
return self.subject.teacher.student_group.room_list
def set_timeslot1(self, new_timeslot):
self.timeslot1 = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lab("
f"id={self.id}, "
f"timeslot1={self.timeslot1}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
#planning_entity
class Lesson(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot=None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot = timeslot
self.room = room
#planning_variable(Base, value_range_provider_refs=['timeslotRangeLS', 'roomRange'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLS"])
def get_timeslot(self):
return self.timeslot
#value_range_provider(range_id = "timeslotRangeLS", value_range_type = Timeslot)
def get_possible_timeslot_list(self):
return self.subject.teacher.student_group.room_list
# return self.course.teacher.department.room_list
def set_timeslot(self, new_timeslot):
self.timeslot = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lesson("
f"id={self.id}, "
f"timeslot={self.timeslot}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
The issue is you defined #value_range_provider(range_id = "timeslotRangeLS") on both your #planning_solution and your #planning_entity. You can only have one; if you want the value range to apply to every entity, do it on the #planning_solution. If you want each planning entity to have it own value range that only applies to it, do it on the #planning_entity. If you want to combine a value range that contains common values for all entities, and a value range that is per entity, use a #value_range_provider on the #planning_solution, and a #value_range_provider on the entity, but give them different ids (ex: #value_range_provider(range_id = "timeslotRangeLSSolution") and #value_range_provider(range_id = "timeslotRangeLSEntity"), and in the #planning_variable, use both range ids in the list (ex: #planning_variable(Room, ["timeslotRangeLSSolution", "timeslotRangeLSEntity"])

Get object from a list in Python?

I am trying to get one account from some branch but somewhere i am missing something. This line is from method -> but the result is <main.SavingAccount object at 0x000001F2563CEFD0>
class Branch:
def __init__(self, branch_code, city):
self.branch_code = branch_code
self.city = city
self.account_list = []
self.loan_list = []
def getAccount(self, acc_no):
for account in self.account_list:
if account.acc_no == acc_no:
return account
print(f2.getAccount(300005))
try this:
class Branch:
def __init__(self, branch_code, city):
self.branch_code = branch_code
self.city = city
self.account_list = []
self.loan_list = []
def getAccount(self, acc_no):
for account in self.account_list:
if account == acc_no:
return account
f2 = Branch(123,"NY")
f2.account_list=[111,222,300005]
print(f2.getAccount(300005))

"TypeError :super() takes at least 1 argument (0 given) " how to solve this i have used argument as a super class name but it didn't worked

students = []
class Student:
school_name = 'Maharshi Science school'
def __init__(self,name,student_id=336):
self.name = name
self.student_id= student_id
students.append(self)
def __str__(self):
return "student: " + self.name
def get_name_capitalize(self):
return self.name.capitalize()
def get_school_name(self):
return self.school_name
class HighschoolStudent(Student):
school_name = 'Maharshi High School'
def get_school_name(self):
return "This is a high school student"
def get_name_capitalize(self):
original_value = super().get_name_capitalize()
return original_value + "-HighschoolStudent"
chirag = HighschoolStudent('chirag')
print(chirag.get_name_capitalize())
This error will only occur if you are using Python 2. To fix this, replace
super().get_name_capitalize()
with
super(HighschoolStudent, self).get_name_capitalize()
If you upgrade to Python 3, your code should work fine.
You are getting the error due to Python 2. Please try the below code:
students = []
class Student(object):
school_name = 'Maharshi Science school'
def __init__(self,name,student_id=336):
self.name = name
self.student_id= student_id
students.append(self)
def __str__(self):
return "student: " + self.name
def get_name_capitalize(self):
return self.name.capitalize()
def get_school_name(self):
return self.school_name
class HighschoolStudent(Student):
school_name = 'Maharshi High School'
def get_school_name(self):
return "This is a high school student"
def get_name_capitalize(self):
original_value = super(HighschoolStudent, self).get_name_capitalize()
return original_value + "-HighschoolStudent"
chirag = HighschoolStudent('chirag')
print(chirag.get_name_capitalize())
Output:
Chirag-HighschoolStudent
There are two changes in this:
class Student --> class Student(object)
Passing your class name as input in super as mandated by Python 2

TypeError: __init__() takes exactly 8 arguments (7 given) Python Homework

I can't figure out why I am getting the TypeError. Below is a class and two sub-classes. The first two work fine. The Final sub-class(OperatingSys) is where I am finding difficulty. I have put my Error input at the very bottom. Thanks in advance!
class InventoryItem(object):
def __init__(self, title, description, price, store_id):
self.title = title
self.description = description
self.price = price
self.store_id = store_id
def __str__(self):
return self.title
def __eq__(self, other):
if self.store_id == other.title:
return True
else:
return False
def change_description(self, description=""):
if not description:
description = raw_input("Please give me a description:")
self.description = description
def change_price(self, price = -1):
while price < 0:
price = raw_input("Please give me the new price [X.XX]: ")
try:
price = float(price)
break
except:
print "I'm sorry but {} isn't valid.".format(price)
self.price = price
def change_title(self, title=""):
if not title:
title = raw_input("Please give me a new title: ")
self.title = title
class Book(InventoryItem):
def __init__(self, title, description, price, format, author, store_id):
super(Book, self).__init__(title=title,
description = description,
price = price,
store_id=store_id)
self.format = format
self.author = author
def __str__(self):
book_line = "{title} by {author}".format(title = self.title, author = self.author)
return book_line
def __eq__(self, other):
if self.title == other.title and self.author == other.author:
return True
else:
return False
def change_format(self, format):
if not format:
format = raw_input("Please give me the new format: ")
self.format = format
def change_author(self, author):
if not author:
author = raw_input("Please give me the enw author: ")
class OperatingSys(InventoryItem):
def __init__(self, InventoryItem, title, price, description, opsys, rating, store_id):
super(OperatingSys, self).__init__(title=title, price=price, description=description, store_id=store_id)
self.opsys = opsys
self.rating = rating
def __str__(self):
opsys_line = "{title} for {OpSys}, price is {price}".format(title = self.title, OpSys=self.OpSys, price = self.price)
return opsys_line
def __eq__(self, other):
if self.title == other.title and self.author == other.author:
return True
else:
return False
def change_opsys(self, opsys):
if not opsys:
opsys = raw_input("Please give me a new Operating System: ")
self.opsys = opsys
def change_rating(self, rating):
if not rating:
rating = raw_input("Plese assign the appropriate rating: ")
self.rating = rating
TheDivision = OperatingSys(title="The Division",description="third person shooter", price=69.99, opsys="", rating="", store_id=3908657)
Traceback (most recent call last):
File "<pyshell#128>", line 1, in <module>
TheDivision = OperatingSys(title="The Division",description="third person shooter", price=69.99, opsys="", rating="", store_id=3908657)
TypeError: __init__() takes exactly 8 arguments (7 given)
When you try and create OperatingSys you are passing in 6 parameters — which together with self make 7:
OperatingSys(
title="The Division", # 1
description="third person shooter", # 2
price=69.99, # 3
opsys="", # 4
rating="", # 5
store_id=3908657 # 6
)
But your definition requires 7 (8 including self):
def __init__(self, InventoryItem, title, price, description, opsys, rating, store_id):
I suspect that the InventoryItem there is a mistake — you don't need to include the parent class as a parameter in the init definition.
def __init__(self, title, price, description, opsys, rating, store_id):

Classes Error Indentation? But where?

this is my product class
class Product(object):
def __init__(self,price,name,catalognum,starRating):
self.price = price
self.name = name
self.catalognum = catalognum
self.starRating = starRating
def __str__():
print "Catalognum:[0]\n\
Name: [1]\n\
Price: $[2]\n\
Rating: [3]".format(catalognum,name,price,num_starRating)
def num_starRating(self):
return "*"*int(self.rating)
class Book(object):
def __init__(self,price,name,catalognum,starRating,author,ISBN,publisher):
self.price = price
self.name = name
self.catalognum = catalognum
self.starRating = starRating
self.author = author
self.ISBN = ISBN
self.publisher = publisher
def __str__():
print "author:[0]\n\
Title:[1]\n\
Price:$[2]\n\
ISBN:[3]\n\
Publisher:[4]\n\
Rating[5]".format(author,Title,Price,ISBN,num_starRating)
class Movie(object):
def __init__(self,Director,Studio,Title,Price,Running_Time,starRating,name,catalognum):
self.Director = Director
self.Studio = Studio
self.Title = Title
self.Price = Price
self.Running_Time = Running_Time
self.starRating = starRating
self.name = name
self.catalognum = catalognum
def __str__():
print "Director:[0]\n\
Title:[1]\n\
Price:[2]\n\
Running_Time:[3]min\n\
Studio:[4]\n\
Rating[5]".format(Director,Title,Price,Running_Time,Studio,num_starRating)
This is my catalog class
class Catalog(object):
def __init__(self,product_file):
self.product_file = product_file
sortByColumn = 0
self.cataloglist = self.BuildCatalogList
def BuildCatalogList(self):
file = open(self.product_file,"r")
filelist = file.readlines()
product_list = []
for i in range(1,len(file_list)):
product = filelist[i].split(',')
item = product(float(product[2]),int(product[3]),product[1],product[0])
product_list.append(item)
return product_list
def setsortby(self,sortype):
self.sortbycolumn = sorttype
def printcatalogtable(self):
print “[0][1][2][3]”.format(“catalog #”,”name”,”price($)”,”rating”)
import os
directory = os.listdir(“.”)
for filename in directory:
if filename [:-3:] == “pyc”:
os.remove(filename)
catalog = catalog(“bookdata.txt)
for printcatalogtable
print”[0:20]][1:25][2:15][3]”.format(“catalog #”,”name”,”price($)”,”rating)
for product in cataloglist:
print “(0:20)(1:25)(2:15.2f) (3)”[3]”.format(product,catalognum,product,name,price,name,product,price,product.getstarrating())
Using two classes, I tried to print out my file i have saved in format that follows catalog class
but its not working out, any ideas?
It should work out like this:
Catalog Number (6 digits),Title,Price,Star Rating (1-5),Author First Name,Author Last Name,ISBN,Publisher
123456,Game of Thrones: A Song of Ice and Fire,11.99,5,George RR,Martin,9780553582017,Random House Publishing Group
654321,City of Bones,11.99,4,Cassandra,Clare,9781406331400,Margaret K McElderry Books
654613,How I Met My Husband,14.99,4,Alice,Munro,2354365435123,Book Bublishers Inc
524638,The Hunger Games,9.99,4,Susan,Collins,9780439023481,Scholastic Press
632356,Lives of the Saints,19.99,2,Ninno,Ricci,8883336666,Harol Hitch Hijackers Books
675031,1984,11.99,5,George,Orwell,1782127755,Secker and Warburg London
111111,Forbidden City,5.99,1,William,Bell,4435-13422453,Lamest Books Corp
315644,Harry Potter and the Prisoner of Azkaban,14.99,5,JK,Rowling,64569-7861-0537,Raincoast
478931,Fifty Shades of Grey,2.99,0,EL,James,783844-6512-982,BooksBooksBooks Inc.
101010,Breaking Dawn,0.99,1,Stephanie,Meyer,101010-1010-101,LOLOLOLOL Press
548573,The Great Gatsby,14.99,4,F Scott,Fitzgerald,9781597226769,Scribners
123827,Steve Jobs,39.99,4.5,Walter,Isaacson,9781451648539,Google Inc
453123,Twilight,0.1,1,Stephenie,Meyer,9781594133299,Simons Inc.
445234,A Midsummer Night's Dream,10.99,3,William,Shakespeare,123455-4322-144,Penguin Group
542324,Paper Town,12.99,2,John,Green,698773-3122-341,Penguin Group
991337,Shutter Island,19.99,4.5,Dennis,Lehane,1234567890154,Awesome Group
123431,The Magic School Bus at the Waterworks,50,5,Joanna ,Cole,0-590-40360-5,Scholastic Corporation
Your BuildCatalogList starts at 0 spaces this should be changed as below (and of course for all the other functions that belong to the class Catalog.
class Catalog(object):
def __init__(self,product_file):
self.product_file = product_file
sortByColumn = 0
self.cataloglist = self.BuildCatalogList
# Spaces added to this function.
def BuildCatalogList(self):
file = open(self.product_file,"r")
filelist = file.readlines()
product_list = []
for i in range(1,len(file_list)):
product = filelist[i].split(',')
item = product(float(product[2]),int(product[3]),product[1],product[0])
product_list.append(item)
return product_list
The indentation of __init__ and __str__ methods of Book and Movie classes are wrong. Indent it properly.

Categories

Resources