How to render DateField with 3 selects - python

I'm looking for the simplest and cleanest way to render a basic DateField with 3 select.
<select>day</select><select>month</select><select>year</select>
(and if possible use "format" to choose how to display the final render)

You can take advantage of the fact that DateField will handle multiple-valued inputs and join them together with a space, so you can avoid a secondary form and instead just provide a sequence of inputs:
from wtforms.widgets.core import Select, HTMLString, html_params
class SelectDateWidget(object):
FORMAT_CHOICES = {
'%d': [(x, str(x)) for x in range(1, 32)],
'%m': [(x, str(x)) for x in range(1, 13)],
'%y': [(x, str(x)) for x in range(1950, 2014)],
}
def __call__(self, field, **kwargs):
field_id = kwargs.pop('id', field.id)
html = []
for format in field.format.split():
choices = self.FORMAT_CHOICES[format]
id_suffix = format.replace('%', '-')
params = dict(kwargs, name=field.name, id=field_id + id_suffix)
html.append('<select %s>' % html_params(params))
if field.data:
current_value = int(field.data.strftime(format))
else:
current_value = None
for value, label in choices:
selected = (value == current_value)
html.append(Select.render_option(value, label, selected))
html.append('</select>')
return HTMLString(''.join(html))
# Usage
class MyForm(Form):
american_date = DateField(format='%m %d %y', widget=SelectDateWidget())
european_date = DateField(format='%d %m %y', widget=SelectDateWidget())

Final widget: (Support multiple format not only spaces)
class SelectDateWidget(object):
FORMAT_CHOICES = {
'%d': [(x, str(x)) for x in range(1, 32)],
'%m': [(x, str(x)) for x in range(1, 13)]
}
FORMAT_CLASSES = {
'%d': 'select_date_day',
'%m': 'select_date_month',
'%Y': 'select_date_year'
}
def __init__(self, years=range(1930, 2014)):
super(SelectDateWidget, self).__init__()
self.FORMAT_CHOICES['%Y'] = [(x, str(x)) for x in years]
def __call__(self, field, **kwargs):
field_id = kwargs.pop('id', field.id)
html = []
allowed_format = ['%d', '%m', '%Y']
for format in field.format.split():
if (format in allowed_format):
choices = self.FORMAT_CHOICES[format]
id_suffix = format.replace('%', '-')
id_current = field_id + id_suffix
kwargs['class'] = self.FORMAT_CLASSES[format]
try: del kwargs['placeholder']
except: pass
html.append('<select %s>' % html_params(name=field.name, id=id_current, **kwargs))
if field.data:
current_value = int(field.data.strftime(format))
else:
current_value = None
for value, label in choices:
selected = (value == current_value)
html.append(Select.render_option(value, label, selected))
html.append('</select>')
else:
html.append(format)
html.append('<input type="hidden" value="'+format+'" %s></input>' % html_params(name=field.name, id=id_current, **kwargs))
html.append(' ')
return HTMLString(''.join(html))

I used a custom widget and it's working but it's not perfect yet. Other ideas to do this?
class SelectDateWidget(object):
class SelectDateForm(Form):
days = [(x,x) for x in range(1,32)]
months = [(x,x) for x in range(1,13)]
years = [(x,x) for x in range(1950,2014)]
days_select = SelectField(choices=days)
month_select = SelectField(choices=months)
year_select = SelectField(choices=years)
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
date_form = self.SelectDateForm(prefix=field.name)
days_html = date_form.days_select(class_="input-mini").__html__()
month_html = date_form.month_select(class_="input-mini").__html__()
year_html = date_form.year_select(class_="input-small").__html__()
widget_html = field.format
widget_html = widget_html.replace('%d', days_html)
widget_html = widget_html.replace('%m', month_html)
widget_html = widget_html.replace('%Y', year_html)
return HTMLString(widget_html)
class SelectDateField(DateField):
widget = SelectDateWidget()
def __init__(self, label=None, validators=None, **kwargs):
super(SelectDateField, self).__init__(label, validators, **kwargs)
def pre_validate(self, extra):
form = SelectDateWidget.SelectDateForm(prefix=self.name)
try:
date = datetime.datetime.strptime(form.days_select.data+'-'+form.month_select.data+'-'+form.year_select.data, '%d-%m-%Y')
self.data = date
except:
raise StopValidation(gettext(u'Invalid date.'))
class MyForm(Form):
date = SelectDateField(u'Date', validators=[Required(message=_(u'This field is required.'))], format='%d / %m / %Y')

Related

Can't print __str__ from the class

I wondered how can I print the class contents of a particular index. I made a class that has all the values of a certain seismic movement and stores each in its own data type.
Here is the class:
import re
class Txt_data:
def __init__(self, result):
self.date = result[0]
self.time = result[1]
self.latit = result[2]
self.long = result[3]
self.depth = result[4]
self.md = result[5]
self.ml = result[6]
self.mw = result[7]
self.region = result[8]
self.method = result[9]
def date(self):
return self._date
def time(self):
return self._time
def latit(self):
return self._latit
def long(self):
return self._long
def depth(self):
return self._depth
def md(self):
return self._md
def ml(self):
return self._ml
def mw(self):
return self._mw
def region(self):
return self._region
def method(self):
return self._method
# This does not work
def __str__(self):
return ('MAG: ' + float(self.ml()) + ' DEPTH: ' + int(self.region()) + ' DATE/TIME: ' + str(self.date()) + ' ' + str(self.time()) + ' LAT: ' + float(self.latit()) + ' LON: ' + float(self.long()))
result = [('2021.12.02', '22:29:24', '36.9605', '28.1775', '13.0', '-.-', '1.5', '-.-', 'KARACA-MARMARIS (MUGLA)', ' Quick')]
print(Txt_data(result))
I was trying to print the data using str method but it doesn't work.
Here is the error:
Traceback (most recent call last):
File "/Users/seyfalsultanov/Documents/uni comp 100/comp100-2021f-ps5-seyfalku/main.py", line 73, in <module>
print(Txt_data(result))
File "/Users/seyfalsultanov/Documents/uni comp 100/comp100-2021f-ps5-seyfalku/main.py", line 60, in __str__
print('MAG: ' + float(self.ml()) + ' DEPTH: ' + int(self.region()) + ' DATE/TIME: ' + str(self.date()) + ' ' + str(self.time()) + ' LAT: ' + float(self.latit()) + ' LON: ' + float(self.long()))
AttributeError: Txt_data instance has no __call__ method
My question is how to print the string i tried to print using str method in the class.
Thanks very much beforehand.
Your immediate problem is that you shadowed all your methods with instance attributes, instead of using _-prefixed names for the attributes that the method expect.
def __init__(self, result):
self._date = result[0]
self._time = result[1]
self._latit = result[2]
self._long = result[3]
self._depth = result[4]
self._md = result[5]
self._ml = result[6]
self._mw = result[7]
self._region = result[8]
self._method = result[9]
However, none of those getters are necessary; just use the instance attributes directly. In __str__, use an f-string to perform any necessary type conversions (which you are currently doing wrong; non-str values need to be converted to str values, not the other way around).
class Txt_data:
def __init__(self, result):
self.date = result[0]
self.time = result[1]
self.latit = result[2]
self.long = result[3]
self.depth = result[4]
self.md = result[5]
self.ml = result[6]
self.mw = result[7]
self.region = result[8]
self.method = result[9]
def __str__(self):
return f'MAG: {self.ml} DEPTH: {self.region} DATE/TIME: {self.date} {self.time} LAT: {self.latit} LON: {self.long}'
result = ('2021.12.02', '22:29:24', '36.9605', '28.1775', '13.0', '-.-', '1.5', '-.-', 'KARACA-MARMARIS (MUGLA)', ' Quick')
print(Txt_data(result))
Finally, I would recommend making __init__ not be responsible for splitting up a list. Have it simply take 10 different arguments, and use a dedicated class method to parse a list in a fixed format.
class Txt_data:
def __init__(self, date, time, latitude, long, depth, md, ml, mw, region, method):
self.date = date
self.time = time
self.latit = latit
self.long = long
self.depth = depth
self.md = md
self.ml = ml
self.mw = mw
self.region = region
self.method = method
#classmethod
def from_list(cls, x):
if len(x) != 10:
raise ValueError("Wrong number of elements in list")
return cls(*x)
def __str__(self):
return f'MAG: {self.ml} DEPTH: {self.region} DATE/TIME: {self.date} {self.time} LAT: {self.latit} LON: {self.long}'

Write a function that returns the name of the currency with the maximum value of the rate

I have to write a function that returns the name of the currency (‘Name’ field) with the maximum value of the rate using the service https://www.cbr-xml-daily.ru/daily_json.js.
Here is what I have done so far:
import requests
class Rate:
def __init__(self, format_='value'):
self.format = format_
def exchange_rates(self):
self.r = requests.get('https://www.cbr-xml-daily.ru/daily_json.js')
return self.r.json()['Valute']
def make_format(self, currency):
response = self.exchange_rates()
if currency in response:
if self.format == 'full':
return response[currency]
if self.format == 'value':
return response[currency]['Value']
return 'Error'
def eur(self):
return self.make_format('EUR')
def usd(self):
return self.make_format('USD')
def brl(self):
return self.make_format('BRL')
r = Rate(format_='value')
r.brl() # 14.1581
r.eur() # 88.1397
But I cannot figure out how to return the currency with the maximum value.
I am not sure why you're creating a class to do this or exactly what you want, but if it's the "Name" with maximum "Value" of all the currencies, you could define a max_rate() class method as shown below:
from operator import itemgetter
import requests
class Rate:
def __init__(self, format_='value'):
self.format = format_
def exchange_rates(self):
self.r = requests.get('https://www.cbr-xml-daily.ru/daily_json.js')
return self.r.json()['Valute']
def max_rate(self):
getter = itemgetter('Name', 'Value')
rates = [getter(info) for info in self.exchange_rates().values()]
return max(rates, key=itemgetter(1)) # Return Name, Value with max Value.
r = Rate()
print(r.max_rate())
I think you need something like this
import requests
class Rate:
def __init__(self, format_='value'):
self.format = format_
def exchange_rates(self):
self.r = requests.get('https://www.cbr-xml-daily.ru/daily_json.js')
return self.r.json()['Valute']
def make_format(self, currency):
response = self.exchange_rates()
if currency in response:
if self.format == 'full':
return response[currency]
if self.format == 'value':
return response[currency]['Value']
return 'Error'
def eur(self):
return self.make_format('EUR')
def usd(self):
return self.make_format('USD')
def brl(self):
return self.make_format('BRL')
def max(self):
x = self.brl()# 14.1581
y = self.eur()# 88.1397
z = self.usd()
if max(x,y,z)==x:
return "Brl"
elif max(x,y,z)==y:
return "EUR"
else:
return "USD"
r = Rate(format_='value')
x = r.brl()# 14.1581
y = r.eur()# 88.1397
z = r.usd()
Max = r.max()
print("Brl ",x)
print("Eur ",y)
print("Usd ",z)
print("Maximum = ",Max)

I got some errors for implementation of GeneticAlgo

I am trying to make a time table scheduling program but found some errors. Please watch the following code and solve that error please.
Errors
These are the following errors
Traceback (most recent call last):
File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 367, in <module>
population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 367, in <lambda>
population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 84, in get_fitness
self._fitness = self.calculate_fitness()
File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 106, in calculate_fitness
if classes[i].get_room().get_seatingCapacity() < classes[i].get_course().get_maxNumbOfStudnets():
AttributeError: 'NoneType' object has no attribute 'get_seatingCapacity'
Source Code of the Program
Variables:
These are the variables which i declare for this program
import prettytable as prettytable
import random as rnd
POPULATION_SIZE = 9
NUMB_OF_ELITE_SCHEDULES = 1
TOURNAMENT_SELECTION_SIZE = 3
MUTATION_RATE = 0.1
Data Class
That is the first class which name is DATA
class Data:
ROOMS = [["R1", 25], ["R2", 45], ["R3", 35]]
MEETING_TIMES = [
["MT1", "MWF 09:00 - 10:00"],
["MT2", "MWF 10:00 - 11:00"],
["MT3", "TTH 09:00 - 10:30"],
["MT4", "TTH 10:30 - 12:00"]
]
INSTRUCTORS = [
["T1", "Dr James Web"],
["T2", "Mr Mike Brown"],
["T3", "Dr Steve Day"],
["T4", "Mrs Jane Doe"]
]
def __init__(self):
self._rooms = []
self._meetingTimes = []
self._instructors = []
for i in range(0, len(self.ROOMS)):
self._rooms.append(Room(self.ROOMS[i][0], self.ROOMS[i][1]))
for i in range(0, len(self.MEETING_TIMES)):
self._meetingTimes.append(MeetingTime(self.MEETING_TIMES[i][0], self.MEETING_TIMES[i][1]))
for i in range(0, len(self.INSTRUCTORS)):
self._instructors.append(Instructor(self.INSTRUCTORS[i][0], self.INSTRUCTORS[i][1]))
course1 = Course("C1", "325k", [self._instructors[0], self._instructors[1]], 25)
course2 = Course("C2", "319k", [self._instructors[0], self._instructors[1], self._instructors[2]], 35)
course3 = Course("C3", "462k", [self._instructors[0], self._instructors[1]], 25)
course4 = Course("C4", "464k", [self._instructors[2], self._instructors[3]], 30)
course5 = Course("C5", "360C", [self._instructors[3]], 35)
course6 = Course("C6", "303k", [self._instructors[0], self._instructors[2]], 45)
course7 = Course("C7", "303L", [self._instructors[1], self._instructors[3]], 45)
self._courses = [course1, course2, course3, course4, course5, course6, course7]
dept1 = Department("MATH", [course1, course3])
dept2 = Department("EE", [course2, course4, course5])
dept3 = Department("PHY", [course6, course7])
self._depts = [dept1, dept2, dept3]
self._numberOfClasses = 0
for i in range(0, len(self._depts)):
self._numberOfClasses += len(self._depts[i].get_courses())
def get_rooms(self):
return self._rooms
def get_instructors(self):
return self._instructors
def get_courses(self):
return self._courses
def get_depts(self):
return self._depts
def get_meetingTimes(self):
return self._meetingTimes
def get_numberOfClasses(self):
return self._numberOfClasses
Schedule Class
That is the second class which name is Schedule
class Schedule:
def __init__(self):
self._data = data
self._classes = []
self._numberOfConflicts = 0
self._fitness = -1
self._classNumb = 0
self._isFitnessChanged = True
def get_classes(self):
self._isFitnessChanged = True
return self._classes
def get_numberOfConflicts(self):
return self._numberOfConflicts
def get_fitness(self):
if(self._isFitnessChanged == True):
self._fitness = self.calculate_fitness()
self._isFitnessChanged = False
return self._fitness
def initialize(self):
depts = self._data.get_depts()
for i in range(0, len(depts)):
courses = depts[i].get_courses() #courses in each departments
for j in range(0, len(courses)):
newClass = Class(self._classNumb, depts[i], courses[j])
self._classNumb += 1
newClass.set_meetingTime(data.get_meetingTimes()[rnd.randrange(0, len(data.get_meetingTimes()))])
newClass.set_room(data.get_rooms()[rnd.randrange(0, len(data.get_rooms()))])
newClass.set_instructor(courses[j].get_instructors()[rnd.randrange(0, len(courses[j].get_instructors()))])
self._classes.append(newClass)
return self
def calculate_fitness(self):
self._numberOfConflicts = 0
classes = self.get_classes()
for i in range(0, len(classes)):
if classes[i].get_room().get_seatingCapacity() < classes[i].get_course().get_maxNumbOfStudnets():
self._numberOfConflicts += 1
for j in range(0, len(classes)):
if(j >= i):
if(classes[i].get_meetingTime() == classes[j].get_meetingTime() and
classes[i].get_id() != classes[j].get_id()):
if(classes[i].get_room() == classes[j].get_room()):
self._numberOfConflicts += 1
if(classes[i].get_instructor() == classes[j].get_instructor()):
self._numberOfConflicts += 1
return 1 / ((1.0*self._numberOfConflicts + 1))
def __str__(self):
# it returns all the classes of schedule separated by comas
returnValue = ""
for i in range(0, len(self._classes)):
returnValue += str(self._classes[i]) + ", "
returnValue += str(self._classes[len(self._classes)-1])
return returnValue
Population Class
Thats the third class which is Population class
class Population:
def __init__(self, size):
self._size = size
self._data = data
self._schedules = []
for i in range(0, size):
self._schedules.append(Schedule().initialize())
def get_schedules(self):
return self._schedules
GeneticAlgorithm Class
Thats the fourth class which is the GeneticAlgorithm class
class GeneticAlgorithm:
def evolve(self, population):
return self._mutate_population(self._crossover_population(population))
def _crossover_population(self, pop):
crossover_pop = Population(0)
for i in range(NUMB_OF_ELITE_SCHEDULES):
crossover_pop.get_schedules().append(pop.get_schedules()[i])
i = NUMB_OF_ELITE_SCHEDULES
while i < POPULATION_SIZE:
schedule1 = self._select_tournament_population(pop).get_schedules()[0]
schedule2 = self._select_tournament_population(pop).get_schedules()[0]
crossover_pop.get_schedules().append(self._crossover_schedule(schedule1, schedule2))
i += 1
return crossover_pop
def _mutate_population(self, population):
for i in range(NUMB_OF_ELITE_SCHEDULES, POPULATION_SIZE):
self._mutate_schedule(population.get_schedules()[i])
return population
def _crossover_schedule(self, schedule1, schedule2):
crossoverSchedule = Schedule().initialize()
for i in range(0, len(crossoverSchedule.get_classes())):
if (rnd.random() > 0.5):
crossoverSchedule.get_classes()[i] = schedule1.get_classes()[i]
else:
crossoverSchedule.get_classes()[i] = schedule2.get_classes()[i]
return crossoverSchedule
def _mutate_schedule(self,mutateSchedule):
schedule = Schedule().initialize()
for i in range(0, len(mutateSchedule.get_classes())):
if(MUTATION_RATE > rnd.random()):
mutateSchedule.get_classes()[i] = schedule.get_classes()[i]
return mutateSchedule
def _select_tournament_population(self, pop):
tournament_pop = Population(0)
i = 0
while i < TOURNAMENT_SELECTION_SIZE:
tournament_pop.get_schedules().append(pop.get_schedules()[rnd.randrange(0, POPULATION_SIZE)])
i += 1
tournament_pop.get_schedules().sort(key=lambda x:x.get_fitness(), reverse=True)
return tournament_pop
Course Class
Thats the fifth class which is the Course class
class Course:
def __init__(self, number, name, instructors, maxNumbOfStudents):
self._number = number
self._name = name
self._instructors = instructors
self._maxNumbOfStudents = maxNumbOfStudents
def get_name(self):
return self._name
def get_number(self):
return self._number
def get_instructors(self):
return self._instructors
def get_maxNumbOfStudents(self):
return self._maxNumbOfStudents
def __str__(self):
return self._name
Instructor Class
Thats the sixth class which is Instructor class
class Instructor:
def __init__(self, id, name):
self._id = id
self._name = name
def get_id(self):
return self._id
def get_name(self):
return self._name
def __str__(self):
return self._name
Room Class
Thats the seventh class which is the Room Class
class Room:
def __init__(self, number, seatingCapacity):
self._number = number
self._seatingCapacity = seatingCapacity
def get_number(self):
return self._number
def get_seatingCapacity(self):
return self._seatingCapacity
MeetingTime Class
Thats the eighth class which is MeetingTime class
class MeetingTime:
def __init__(self, id, time):
self._time = time
self._id = id
def get_id(self):
return self._id
def get_time(self):
return self._time
Department Class
Thats the ninth class which is the Department class
class Department:
# Batch for my case
def __init__(self, name, courses):
self._name = name
self._courses = courses # Courses that department offers
def get_name(self): return self._name
def get_courses(self): return self._courses
Class class
Thats is the tenth class which name is Class
class Class:
# Course to be scheduled at specific room of department host by an instructor at specific Meeting Time
def __init__(self, id, dept, course):
self._id = id
self._dept = dept
self._course = course
self._instructor = None
self._meetingTime = None
self._room = None
def get_id(self):
return self._id
def get_dept(self):
return self._dept
def get_room(self):
return self._room
def get_course(self):
return self._course
def get_instructor(self):
return self._instructor
def get_meetingTime(self):
return self._meetingTime
def set_instructor(self, instructor):
self._instructor = instructor
def set_meetingTime(self, meetingTime):
self._meetingTime = meetingTime
def set_room(self, room):
self_room = room
def __str__(self):
return str(self._dept.get_name()) + "," + str(self._course.get_number()) + "," + \
str(self._room.get_number()) + "," + str(self._instructor.get_id()) + "," + str(self._meetingTime.get_id())
DisplayMgr Class Plus End Code
Thats the eleventh class which is DisplayMgr Class and the end code of that program.
class DisplayMgr:
def print_available_data(self):
print("> All Available Data")
self.print_dept()
self.print_course()
self.print_room()
self.print_instructor()
self.print_meeting_times()
def print_dept(self):
depts = data.get_depts()
availableDeptsTable = prettytable.PrettyTable(['dept', 'courses'])
for i in range(0, len(depts)):
courses = depts.__getitem__(i).get_courses()
tempStr = "["
for j in range(0, len(courses) - 1):
tempStr += courses[j].__str__() + ", "
tempStr += courses[len(courses) - 1].__str__() + "]"
availableDeptsTable.add_row([depts.__getitem__(i).get_name(), tempStr])
print(availableDeptsTable)
def print_course(self):
availabelCoursesTable = prettytable.PrettyTable(['id', 'course # ', 'max # of students', 'instructors'])
courses = data.get_courses()
for i in range(0, len(courses)):
instructors = courses[i].get_instructors()
tempStr = ""
for j in range(0, len(instructors)-1):
tempStr += instructors[j].__str__() + ", "
tempStr += instructors[len(instructors) - 1].__str__()
availabelCoursesTable.add_row(
[courses[i].get_number(), courses[i].get_name(), str(courses[i].get_maxNumbOfStudents()), tempStr]
)
print(availabelCoursesTable)
def print_instructor(self):
availableInstructorsTable = prettytable.PrettyTable(['id', 'instructor'])
instructors = data.get_instructors()
for i in range(0, len(instructors)):
availableInstructorsTable.add_row([instructors[i].get_id(), instructors[i].get_name()])
print(availableInstructorsTable)
def print_room(self):
availableRoomsTable = prettytable.PrettyTable(['room #', 'max seating capacity'])
rooms = data.get_rooms()
for i in range(0, len(rooms)):
availableRoomsTable.add_row([str(rooms[i].get_number()), str(rooms[i].get_seatingCapacity())])
print(availableRoomsTable)
def print_meeting_times(self):
availableMeetingTimeTable = prettytable.PrettyTable(['id', 'Meeting Time'])
meetingTimes = data.get_meetingTimes()
for i in range(0, len(meetingTimes)):
availableMeetingTimeTable.add_row([meetingTimes[i].get_id(), meetingTimes[i].get_time()])
print(availableMeetingTimeTable)
def print_generation(self, population):
table1 = prettytable.PrettyTable(['schedule # ', 'fitness', '# of Conflicts','classes [dept, class, room, instructor'])
schedules = population.get_schedules()
for i in range(0, len(schedules)):
table1.add_row([str(i), round(schedules[i].get_fitness(),3), schedules[i].get_numberOfConflicts(), schedules[i]])
print(table1)
def print_schedule_as_table(self, schedule):
classes = schedule.get_classes()
table = prettytable.PrettyTable(['Class # ', 'Dept', 'Course (number, max # of students)', 'Room (Capacity', 'Instructor'])
for i in range(0, len(classes)):
table.add_row([str(i), classes[i].get_dept().get_name(), classes[i].get_course().get_name() + " (" +
classes[i].get_course().get_number() + ", " +
str(classes[i].get_course().get_maxNumbOfStudents()) + ")",
classes[i].get_room().get_number() + " (" + str(classes[i].get_room().get_seatingCapacity()) +
classes[i].get_instructor().get_name() + " (" + str(classes[i].get_instructor().get_id()) +")",
classes[i].get_meatingTime().get_time() + " (" + str(classes[i].get_meatingTime().get_id()) +")"
])
print(table)
data = Data()
displayMgr = DisplayMgr()
displayMgr.print_available_data()
generationNumber = 0
print("\n> Generation # " + str(generationNumber))
population = Population(POPULATION_SIZE)
population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
displayMgr.print_generation(population)
displayMgr.print_schedule_as_table(population.get_schedules()[0]) # it will print fittest generation of schedule
geneticAlgorithm = GeneticAlgorithm()
while (population.get_schedules()[0].get_fitness() != 1.0):
generationNumber += 1
print("\n> Generation # " + str(generationNumber))
population = geneticAlgorithm.evolve(population)
population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
displayMgr.print_generation(population)
displayMgr.print_schedule_as_table(population.get_schedules()[0])
print("\n\n")
def set_room(self, room):
self_room = room
you have missing . in set_room(self,room) function . Change it to self._room=room so that it will set the room value and objectType=None will be solved
Look into your the class DisplayMgr/def print_schedule_as_table
Change classes[i].get_meatingTime().get_time() to meetingTime

Instances of class polynomial

How can I get coefficients to list from three different ways of creating new instances of class Polynomial?
class Polynomial(object)
def __init__(self,*args)
self.coeffs=[]
...
pol1 = Polynomial([1,-3,0,2])
pol2 = Polynomial(1,-3,0,2)
pol3 = Polynomial(x0=1,x3=2­,x1=-3)
I am expecting for example: pol2 = Polynomial(1,-3,0,2), output is 2x^3-3x+1. But I need to get coefficients to list to work with them.
Assuming, that one of the three ways is always used, you can do the following (without any validation):
class Polynomial(object):
def __init__(self, *args, **kwargs):
if args and isinstance(args[0], list): # Polynomial([1,-3,0,2])
self.coeffs=args[0]
elif args: # Polynomial(1,-3,0,2)
self.coeffs=args
else: # Polynomial(x0=1,x3=2­,x1=-3)
self.coeffs=[kwargs.get(x, 0) for x in ('x0', 'x1', 'x2', 'x3')]
def __str__(self):
s = ''
for i, x in reversed(list(enumerate(self.coeffs))):
if x:
if x > 0:
s += '+'
s += str(x)
if i > 0:
s += 'x'
if i > 1:
s += '^' + str(i)
return '0' if not s else s.lstrip('+')
pol1 = Polynomial([1,-3,0,2])
pol2 = Polynomial(1,-3,0,2)
pol3 = Polynomial(x0=1, x1=-3, x3=2)
print(pol1) # 2x^3-3x+1
print(pol2) # 2x^3-3x+1
print(pol3) # 2x^3-3x+1
In addition to schwobaseggl's response, I'd add this kind of checking:
if type(args[0]) == list:
self.coeffs=args
# ...
else:
self.coeffs=[kwargs.get(x, 0) for x in ['x'+i for i in range(len(kwargs))]]

How to make this Python class definition code less ugly

What's the most idiomatic way to write a class definition? There's no way that my code below is the best way to do this.
class Course:
crn = course = title = tipe = cr_hours = seats = instructor = days = begin = end = location = exam = ""
def __init__(self, pyQueryRow):
self.crn = Course.get_column(pyQueryRow, 0)
self.course = Course.get_column(pyQueryRow, 1)
self.title = Course.get_column(pyQueryRow, 2)
self.tipe = Course.get_column(pyQueryRow, 3)
self.cr_hours = Course.get_column(pyQueryRow, 4)
self.seats = Course.get_column(pyQueryRow, 5)
self.instructor = Course.get_column(pyQueryRow, 6)
self.days = Course.get_column(pyQueryRow, 7)
self.begin = Course.get_column(pyQueryRow, 8)
self.end = Course.get_column(pyQueryRow, 9)
self.location = Course.get_column(pyQueryRow, 10)
self.exam = Course.get_column(pyQueryRow, 11)
def get_column(row, index):
return row.find('td').eq(index).text()
[First of all python is an awesome language. This is my first project using python and I've made a ridiculous amount of progress already.]
def__init__(self, pyQueryRow):
for i,attr in enumerate("crn course title tipe cr_hours seats instructor"
" days begin end location exam".split()):
setattr(self, attr, self.get_column(pyQueryRow, i))
This way avoids multiple calls to self.get_column
def__init__(self, pyQueryRow):
attrs = ("crn course title tipe cr_hours seats instructor"
" days begin end location exam".split())
values = [td.text for td in pyQueryRow.find('td')]
for attr, value in zip(attrs, values):
setattr(self, attr, value)
Personally, I'd use a dictionary to map the property to column numbers:
class Course:
crn = course = title = tipe = cr_hours = seats = instructor = days = begin = end = location = exam = ""
def __init__(self, pyQueryRow):
course_row_mapping = {
'crn' : 0,
'course' : 1,
'title' : 2,
'tipe' : 3, # You probably mean "type"?
'cr_hours' : 4,
'seats' : 5,
'instructor' : 6,
'days' : 7,
'begin' : 8,
'end' : 9,
'location' : 10,
'exam' : 11,
}
for name, col in course_row_mapping.iteritems():
setattr(self, name, Course.get_column(pyQueryRow, col))
def get_column(row, index):
return row.find('td').eq(index).text()
I'm not sure that there is a "better" way. What you have is certainly quite readable. If you wanted to avoid duplicating the Course.get_column code you could define a lambda for that, as in Matthew Flaschen's answer, eg.
class Course:
def __init__(self, pyQueryRow):
get_column = lambda index: pyQueryRow.find('td').eq(index).text()
self.crn = get_column(0)
self.course = get_column(1)
self.title = get_column(2)
self.tipe = get_column(3)
self.cr_hours = get_column(4)
self.seats = get_column(5)
self.instructor = get_column(6)
self.days = get_column(7)
self.begin = get_column(8)
self.end = get_column(9)
self.location = get_column(10)
self.exam = get_column(11)
Note that you don't need the line that initialises all the fields to "" beforehand - just setting them in __init__ is fine. Edit: in fact, as Matthew says, that sets class fields, not instance fields - I totally missed that.
EDIT: Actually, the best might be:
self.crn, self.course, self.title, self.tipe, self.cr_hours, self.seats,\
self.instructor, self.days, self.begin, self.end, self.location, self.exam = \
[pq(td).text() for td in pyQueryRow.find('td')]
That assumes you've imported PyQuery as pq. This avoids ever using indices at all.
self.crn, self.course, self.title, self.tipe, self.cr_hours, self.seats,\
self.instructor, self.days, self.begin, self.end, self.location, self.exam = \
map(lambda index: get_column(pyQueryRow, index), xrange(0, 12))
or if you want a list comprehension:
self.crn, self.course, self.title, self.tipe, self.cr_hours, self.seats,\
self.instructor, self.days, self.begin, self.end, self.location, self.exam = \
[get_column(pyQueryRow, index) for index in xrange(0, 12)]
I don't know if these are the most idiomatic, but there's definitely less boilerplate.
Also, remove the crn = course =. You're assigning to the class, not the instance.
Personally I feel a class shouldn't really know about the outside world. So move it all out and your class looks much prettier. And also more reusable.
class Course:
def __init__(
self,
crn="",
course="",
title="",
tipe="",
cr_hours="",
seats="",
instructor="",
days="",
begin="",
end="",
location="",
exam=""
):
self.crn = crn
self.course = course
self.title = title
self.tipe = tipe
self.cr_hours = cr_hours
self.seats = seats
self.instructor = instructor
self.days = days
self.begin = begin
self.end = end
self.location = location
self.exam = exam
def course_from_row(row):
column_mapping = {
'crn': 0,
'course': 1,
'title': 2,
'tipe': 3,
'cr_hours': 4,
'seats': 5,
'instructor': 6,
'days': 7,
'begin': 8,
'end': 9,
'location': 10,
'exam': 11
}
course = {}
for attr, col in column_mapping.items():
course[attr] = row.find('td').eq(col).text()
return Course(**course)

Categories