I have the following code and it works until it gets to the 'union.set()' part. It says, "unhashable type: 'LinkedEdge' " . I am not sure why this is the case since I have looked at other sources on the web and in reference books to know that the 'g.addVertex()' method and the 'g.addEdge()' method as well as the arguments being passed should lead correctly to an output like this:
5 Vertices: A C B E D
5 Edges: A>B:3 A>C:2 B>D:1 C>D:1 D>E:2
class LinkedEdge(object):
def __init__(self, fromVertex, toVertex, weight = None):
self._vertex1 = fromVertex
self._vertex2 = toVertex
self._weight = weight
self._mark = False
def clearMark(self):
self._mark = False
def __eq__(self, other):
if self is other: return True
if type(self) != type(other):
return False
return self._vertex1 == other._vertex1 and self._vertex2 == other._vertex2
def getOtherVertex(self, thisVertex):
if thisVertex == None or thisVertex == self._vertex2:
return self._vertex1
else:
return self._vertex2
def getToVertex(self):
return self._vertex2
def getWeight(self):
return self._weight
def isMarked(self):
return self._mark
def setMark(self):
self._mark = True
def setWeight(self, weight):
self._weight = weight
def __str__(self):
return str(self._vertex1) + ">" + str(self._vertex2) + ":" + str(self._weight)
class LinkedVertex(object):
def __init__(self, label):
self._label = label
self._edgeList = []
self._mark = False
def clearMark(self):
self._mark = False;
def getLabel(self):
return self._label
def isMarked(self):
return self._mark
def setLabel(self, label, g):
g._vertices.pop(self._label, None)
g._vertices[label] = self
self._label = label
def setMark(self):
self._mark = True
def __str__(self):
return str(self._label)
def addEdgeTo(self, toVertex, weight):
edge = LinkedEdge(self, toVertex, weight)
self._edgeList.append(edge)
def getEdgeTo(self, toVertex):
edge = LinkedEdge(self, toVertex)
try:
return self._edgeList[self._edgeList.index(edge)]
except:
return None
def incidentEdges(self):
return iter(self._edgeList)
def neighboringVertices(self):
vertices = []
for edge in self._edgeList:
vertices.append(edge.getOtherVertex(self))
return iter(vertices)
def removeEdgeTo(self, toVertex):
edge = LinkedEdge(self, toVertex)
if edge in self._edgeList:
self._edgeList.remove(edge)
return True
else:
return False
class LinkedDirectedGraph(object):
def __init__(self, collection = None):
self._vertexCount = 0
self._edgeCount = 0
self._vertices = {}
if collection != None:
for label in collection:
self.addVertex(label)
# Methods for clearing, marks, sizes, string rep
def clear(self):
self._vertexCount = 0
self._edgeCount = 0
self._vertices = {}
def clearEdgeMarks(self):
for edge in self.edges():
edge.clearMark()
def clearVertexMarks(self):
for vertex in self.vertices():
vertex.clearMark()
def isEmpty(self):
return self._vertexCount == 0;
def sizeEdges(self):
return self._edgeCount
def sizeVertices(self):
return self._vertexCount
def __str__(self):
result = str(self.sizeVertices()) + " Vertices: "
for vertex in self._vertices:
result += " " + str(vertex)
result += "\n";
result += str(self.sizeEdges()) + " Edges: "
for edge in self.edges():
result += " " + str(edge)
return result
def addVertex(self, label):
self._vertices[label] = LinkedVertex(label)
self._vertexCount += 1
def containsVertex (self, label):
return label in self._vertices
def getVertex(self, label):
return self._vertices[label]
def removeVertex(self, label):
removedVertex = self._vertices.pop(label, None)
if removedVertex is None:
return False
# Examine all vertices
for vertex in self.vertices():
if vertex.removeEdgeTo(removedVertex):
self._edgeCount -= 1
self._vertexCount -= 1
return True
def addEdge(self, fromLabel, toLabel, weight):
fromVertex = self.getVertex(fromLabel)
toVertex = self.getVertex(toLabel)
fromVertex.addEdgeTo(toVertex, weight)
self._edgeCount += 1
def containsEdge(self, fromLabel, toLabel):
return self.getEdge(fromLabel, toLabel) != None
def getEdge(self, fromLabel, toLabel):
fromVertex = self._vertices[fromLabel]
toVertex = self._vertices[toLabel]
return fromVertex.getEdgeTo(toVertex)
def removeEdge (self, fromLabel, toLabel):
fromVertex = self.getVertex(fromLabel)
toVertex = self.getVertex(toLabel)
edgeRemovedFlg = fromVertex.removeEdgeTo(toVertex)
if edgeRemovedFlg:
self._edgeCount -= 1
return edgeRemovedFlg
# Iterators
def edges(self):
result = set()
for vertex in self.vertices():
edges = vertex.incidentEdges()
result = result.union(set(edges))
return iter(result)
def vertices(self):
return iter(self._vertices.values())
def incidentEdges(self, label):
return self._vertices[label].incidentEdges()
def neighboringVertices(self, label):
return self._vertices[label].neighboringVertices
g = LinkedDirectedGraph()
# Insert vertices
g.addVertex("John")
g.addVertex("Sam")
g.addVertex("Megan")
g.addVertex("Jennifer")
g.addVertex("Rick")
# Insert weighted edges
g.addEdge("John", "Sam", 3)
g.addEdge("John", "Megan", 2)
g.addEdge("Sam", "Jennifer", 1)
g.addEdge("Megan", "Jennifer", 1)
g.addEdge("Jennifer", "Rick", 2)
print(g)
If you override __eq__, then Python intentionally makes your class unhashable, since there is no longer a guarantee that the default hashing algorithm (based on the object's location in memory) is compatible with your __eq__ algorithm. "Compatible" here just means that equal objects must have equal hashes. By default, nothing is equal, so when you make some things equal using an __eq__ method, you impose a requirement on what a proper hash function must do.
If you want a custom class with a custom __eq__ method to be hashable, you must implement a __hash__ method yourself.
It could be as simple as being based on the hash of the corresponding tuple:
def __hash__(self):
return hash((type(self), self._vertex1, self._vertex2))
The Python docs explain this here.
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
I am trying to use BFS to search through a tree with three letter words and find the way in between a given start and end word and print the way in between. The printing is supposed to be done with a recursive function.
I keep getting this error:
RecursionError: maximum recursion depth exceeded while calling a Python object
and an infinite loop with the endword can anyone see whats wrong? (I copied my imported classes as well).
from array import array
class Node1:
#håller koll på värdena
def __init__(self, data, next = None):
self.data = data
self.next = next
def __str__(self):
if self.data.parent == None:
return None
else:
print(self.data.parent)
return str(self.data.parent)
def __str__(self):
return str(self.data.word)
class Queue:
def __init__(self):
self.first = None
self.last = None
def enqueue(self,x):
"""Stoppar in x sist i kön """
x = Node1(x)
if self.first == None: # Om kön är tom
self.first = self.last = x
else: # om kön inte är tom
self.last.next = x
self.last = x
def dequeue(self):
first = self.first
self.first = self.first.next
#if self.first == None:
# self.last=None
return first
def isEmpty(self):
if self.first == None:
xx = True
else:
xx = False
#print('I IsEmpty: Första elementet i listan:',self.first)
#print('I IsEmpty: Sista elementet i listan:',self.last)
return xx
def __str__(self):
node=self.first
node_strang = 'Efter trolleriet får man: '
while node != None:
node_strang += str(node)
node = node.next
return node_strang
class Node:
'''Nodklass med rekursiva metoder som anropas i Bintree-klassen'''
def __init__(self, word):
self.word = word
self.left = None
self.right = None
def insert(self, new_word):
if self.word == new_word:
return False
elif new_word < self.word:
if self.left:
return self.left.insert(new_word)
else:
self.left = Node(new_word)
return True
else:
if self.right:
return self.right.insert(new_word)
else:
self.right = Node(new_word)
return True
def find(self, new_word):
if self.word == new_word:
return True
elif new_word < self.word:
if self.left:
return self.left.find(new_word)
else:
return False
else:
if self.right:
return self.right.find(new_word)
else:
return False
def preorder(self):
if self:
print(self.word)
if self.left:
self.left.preorder()
if self.right:
self.right.preorder()
def postorder(self):
if self:
if self.left:
self.left.postorder()
if self.right:
self.right.postorder()
print(self.word)
def inorder(self):
if self:
if self.left:
self.left.inorder()
print(self.word)
if self.right:
self.right.inorder()
from linkedQFile import Queue,Node1
from bintreeFile import Node
import string
class Bintree:
def __init__(self):
self.root = None
def put(self, new_word):
if self.root:
return self.root.insert(new_word)
else:
self.root = Node(new_word)
return True
def __contains__(self, new_word):
if self.root:
return self.root.find(new_word)
else:
return False
class ParentNode:
def __init__(self, word, parent = None):
self.word = word
self.parent = parent
def maketree():
svenska = Bintree()
gamla = Bintree()
with open('word3.txt', 'r') as ordfil:
for rad in ordfil:
ord = rad.strip()
if ord in svenska:
gamla.put(ord)
svenska.put(ord)
ordfil.close()
return svenska,gamla
def writechain(kidzen, paronen):
if paronen is not None:
print(kidzen)
writechain(kidzen, paronen)
else:
pass
def countchain(barn_obj):
if barn_obj.parent==None:
return 0
else:
return 1+countchain(barn_obj.parent)
def makechildren(nod, q, gamla, svenska):
for i in range(3):
bokstavslista = list(nod.data.word)
alfabetslista = list(string.ascii_lowercase) + ['å', 'ä', 'ö']
for bokstav in alfabetslista:
bokstavslista[i] = bokstav
barn = ''.join(bokstavslista)
if barn in svenska:
barn_obj = ParentNode(barn, nod.data)
#print('parent to', barn, 'is', str(barn_obj.parent))
if barn not in gamla:
#print("i makechildren: barn = ", barn)
q.enqueue(barn_obj)
gamla.put(barn_obj.word)
def main():
(svenska,gamla) = maketree()
q=Queue()
start = input('Startord:')
slut = input('Slutord:')
startord= ParentNode(start, parent=None)
q.enqueue(startord)
while not q.isEmpty():
nod = q.dequeue()
makechildren(nod, q, gamla, svenska)
nod_for=nod.data
kidzen=nod_for.word
paronen=nod_for.parent
#print ('word =', kidzen)
#print ('parent =', paronen)
if q.isEmpty():
print('Det finns ingen väg till', slut)
break
elif kidzen==slut:
writechain(kidzen, paronen)
print('Det finns en väg till', slut)
break
main()
In your writechain function you are not walking a tree.
You keep recursively calling it with the same arguments. That will continue until you reach the recursion limit.
I've been trying the recursive approach but been stuck for too long. I cant tell if it's my BST code that's wrong or my recursion.
Regardless of how many elements I put in my tree I still get the value 2 from my height function.
class Treenode:
def __init__(self, value = None, rchild = None, lchild = None):
self.value = value
self.rchild = rchild
self.lchild = lchild
class bin_tree:
def __init__(self):
self.root = None
def put(self, x):
if self.root is None:
self.root = Treenode(x)
return True
if self.exists(x) == True:
return False
p = self.root
while True:
if x < p.value:
if p.lchild is None:
p.lchild = Treenode(x)
return True
else:
p = p.lchild
elif x > p.value:
if p.rchild is None:
p.rchild = Treenode(x)
return True
else:
p = p.rchild
return
def exists(self, x):
p = self.root
while True and p != None:
if p.value == x:
return True
elif p.value > x and p.lchild != None:
p = p.lchild
elif p.value < x and p.rchild != None:
p = p.rchild
else:
return False
def isempty(self):
return self.root == None
def height(self):
def gh(enrot):
if enrot == None:
return 0
else:
return 1 + max(gh(enrot.lchild), gh(enrot.rchild))
return gh(self.root)
Example code:
from Bintree import *
p = bin_tree()
x = input()
for word in x.split():
p.put(word)
a = input()
if p.exists(a) is True:
print('Exists!')
else:
print('Does not exist!')
print(p.isempty())
print(p.height())
The height method is fine. In your put method, you stop without actually adding the element, so the height doesn't actually grow beyond 2:
def put(self, x):
...
while True:
if x < p.value:
...
elif x > p.value:
if p.rchild is None:
...
else:
p = p.rchild
return
# ^^^^^^ This shouldn't be here.
I'm trying to make a Python module like this:
class square:
def _init_(self):
self._length = 0
self._perimeter = 0
self._area = 0
def setLength(self, length):
self._length = float(length)
self._perimeter = 0
self._area = 0
def getLength(self):
return self._length
def getPerimeter(self):
if self._perimeter == 0:
self._perimeter = float(self._length * 4)
return self._perimeter
def getArea(self):
if self._area == 0:
self._area = float(self._length * self._length)
return self._area
class rectangle:
def _init_(self):
self._length = 0
self._width = 0
self._perimeter = 0
self._area = 0
def setLength(self, length):
self._length = float(length)
self._perimeter = 0
self._area = 0
def getLength(self):
return self._length
def setWidth(self, width):
self._width = float(width)
self._perimeter = 0
self._area = 0
def getWidth(self):
return self._width
def getPerimeter(self):
if self._perimeter == 0:
perim1 = float(self._length * 2)
perim2 = float(self._width * 2)
self._perimeter = float(perim1 + perim2)
return self._perimeter
def getArea(self):
if self._area == 0:
self._area = float(self._length * self._width)
return self._area
class circle:
def _init_(self):
self._radius = 0
self._diameter = 0
self._circumference = 0
self._pi = 3.14159265
def setRadius(self, radius):
self._radius = float(radius)
self._diameter = float(self._radius * 2)
self._circumference = 0
def setDiameter(self, diameter):
self._diameter = float(diameter)
self._radius = float(self._diameter / 2)
self._circumference = 0
def getRadius(self):
return self._radius
def getDiameter(self):
return self._diameter
def getPi(self):
return self._pi
def getCircumference(self):
if self._circumference == 0:
self._circumference = float(self._diameter * self._pi)
return self._circumference
class triangle:
def _init_(self):
self._side = []
self._side[0] = 0
self._side[1] = 0
self._side[2] = 0
self._side[3] = 0
self._angle = []
self._angle[0] = 0
self._angle[1] = 0
self._angle[2] = 0
self._angle[3] = 0
self._perimeter = 0
self._area = 0
def setSide(self, side, length):
self._side[side] = float(length)
def getSide(self, side):
return self._side[side]
def getPerimeter(self):
if self._perimeter == 0:
self._perimeter = side[1] + side[2] + side[3]
return self._perimeter
def setAngle(self, angle, measure):
self._angle[angle] = float(measure)
def getAngle(self, angle):
if self._angle[angle] == 0:
if angle == 1:
angle1 = self._angle[2]
angle2 = self._angle[3]
elif angle == 2:
angle1 = self._angle[1]
angle2 = self._angle[3]
elif angle == 3:
angle1 = self._angle[1]
angle2 = self._angle[2]
anglet = angle1 + angle2
angler = float(180) - anglet
self._angle[angle] = angler
return self.angle[angle]
It's part of a package named Mathworks. The calling code is this:
import mathworks as mw
mycircle = mw.shapes.circle()
mycircle.setDiameter(5)
circum = mycircle.getCircumference()
print circim
When I try two run the second module, I get this:
Traceback (most recent call last):
File "<string>", line 254, in run_nodebug
File "<module1>", line 21, in <module>
File "<module1>", line 17, in main
File "C:\Python27\lib\site-packages\mathworks\shapes.py", line 70, in getCircumference
self._circumference = float(self._diameter * self._pi)
AttributeError: circle instance has no attribute '_pi'
What's wrong? It works if I replace self._pi with 3.14159265, but I need it to work the other way.
You didn't name your initializers correctly, it needs double underscores on either end:
def __init__(self):
You need to correct that for all your classes.
Because you didn't name them correctly, they are not being run when you create an instance of your classes.
Next problem you'll run into is your triangle initializer; you cannot address indexes in an empty list. Create the whole list in one go instead:
def __init__(self):
self._side = [0, 0, 0, 0]
self._angle = [0, 0, 0, 0]
self._perimeter = 0
self._area = 0
You have the constructor written incorrectly. It should be __init__, not _init_, i.e. double underscores.
Because you wrote it wrong, it's not being called, so those attributes aren't being created when you instantiate your objects.