I tried to make this implementation clear. So I created hasChild function of Node. But why am I getting this this error?
'NoneType' object has no attribute 'hasChild'
class Node():
def __init__(self,word):
self.value = str(word)
self.children = {}
self.isEndOfWord = False
def hasChild(self,ch):
return ch in self.children.keys()
def addChild(self,ch):
nodenew = Node(str(ch))
self.children[ch] = nodenew
def getChild(self,ch):
return self.children.get(ch)
class Trie():
def __init__(self):
self.root = Node('')
def insert(self,children):
current = self.root
for ch in children:
if (current.hasChild(ch) is False):
current.addChild(ch)
current = self.root.getChild(ch)
current.isEndOfWord = True
I changed current.hasChild(ch) is False into not current.hasChild(ch) and current = self.root.getChild(ch) into current = current.getChild(ch) of the insert function. It works. Thanks a lot!
class Node():
def __init__(self,word):
self.value = str(word)
self.children = {}
self.isEndOfWord = False
def hasChild(self,ch):
return ch in self.children.keys()
def addChild(self,ch):
nodenew = Node(ch)
self.children[ch] = nodenew
def getChild(self,ch):
return self.children.get(ch)
class Trie():
def __init__(self):
self.root = Node('')
def insert(self,children):
current = self.root
for ch in children:
if (not current.hasChild(ch)):
current.addChild(ch)
current = current.getChild(ch)
current.isEndOfWord = True
trie = Trie()
trie.insert('cat')
trie.insert('can')
Related
This is my code about breadth first search to calculate word error rate[enter image description here](https://i.stack.imgur.com/SV1ow.png)
class FIFOQueue :
def __init__(self) -> None:
self.__queue = []
def append(self,item_in) :
self.__queue.append(item_in)
def extend(self,old_queue):
self.__queue.extend(old_queue)
def pop(self):
return self.__queue.pop(0) # It will be return node
def is_empty(self) :
return self.__queue ==[]
class TreeNode:
def __init__(self,state, step = 0 ,parent=None) -> None:
self.state = tuple(state)
self.step = step
self.parent = parent
def get_state(self):
return self.state
def get_parent(self) :
return self.parent
class RNode(TreeNode) :
def __init__(self, state, step = 0, parent=None) -> None:
super().__init__(state, step, parent)
def expand(self,rp) :
child_list = []
for new_state in rp.adjacent_states(self.state, self.step) :
child_list.append(RNode(new_state, self.step+1, self))
for i in child_list :
print(i.get_state())
return child_list
class RoutingProb : #change
def __init__(self,initial,destination) -> None:
self.initial = initial
self.destination = destination
des = ''
for i in destination :
des += i
self.des_str = des
def is_destination(self,state) :
check_state = ''
for i in state :
if i is None :
continue
else :
check_state += i
return self.des_str == check_state
def adjacent_states(self,state, step) :
return RoutingProb.add_action(self, list(state), step, self.destination)
def add_action(self, state_li, step, des) :
print(step)
print(state_li)
if state_li[step] == des[step]:
print('pass')
print(state_li)
return [state_li]
if len(state_li) > len(des) : #del or sub
state_li2 = state_li[:]
state_li[step] = None #del
state_li2[step] = des[step] #sub
# print('pass2')
return [state_li, state_li2]
elif len(state_li) < len(des) : # ins or sub
state_li2 = state_li[:]
state_li.insert(step, des[step]) #ins
state_li2[step] = des[step] #sub
# print('pass3')
return [state_li, state_li2]
else : # len(state_li) = len(des) only sub
#print('pass4')
state_li[step] = des[step]
return [state_li]
def breadth_first_search(prob):
fringe = FIFOQueue()
fringe.append(RNode(prob.initial))
reaeched ={}
while not fringe.is_empty():
node = fringe.pop()
# print(node.state)
if prob.is_destination(node.state) :
print('xx')
return node
if node.state not in reaeched :
reaeched[node.state] = node
print(reaeched)
fringe.extend(node.expand(prob))
print('x')
def P5_wer(ref,test):
ref_list = [i for i in ref]
test_list = [i for i in test]
rPorb = RoutingProb(test_list,ref_list)
leave_node = breadth_first_search(rPorb)
# print('leave=',leave_node)
x, sol_path = leave_node, [leave_node]
# print('x=',x.get_state)
while x.get_parent() is not None :
sol_path.append(x.get_parent())
x = x.get_parent()
if __name__ == '__main__':
wer, n = P5_wer("grit", "greet")
print("wer = {}, n = {}".format(wer, n))
This is my homework about searching in Introduction to machine learning but it worst course because
they didn't teach me about basic like data structure and Object Oriented Programming. I try my best
I don’t know why it not work
class Node:
def __init__(self,data = None, Next = None):
self.data = data
self.Next = Next
class LinkedList:
def __init__(self):
self.head = None
def insertAtBegining(self,data):
node = Node(data,self.head)
self.head = node
def Print(self):
if self.head == None:
print("Empty Linkelist")
itr = self.head
lstr = ''
while itr:
lstr += str(itr.data) + '-->'
itr = itr.next
print (lstr)
if __name__ == '__main__':
obj1 = LinkedList()
obj1.insertAtBegining(5)
obj1.insertAtBegining(10)
obj1.insertAtBegining(15)
obj1.Print()
I am getting error in Node class saying it does not have next attribute.
It doesn't have next, it has Next, which are different, you can either change itr.next to itr.Next, or (better, to be consistent with your naming) change your Node definition to this:
class Node:
def __init__(self, data = None, next = None):
self.data = data
self.next = next
I am writing a code to search for elements in a binary search tree.
I wrote the code inside the class BinarySearchTree but it returns None.
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
class BinarySearchTree:
def __init__(self):
self.root = None
def search(self, key):
a = search(self.root)
if self.root is None or self.root == key:
return self.root
if key > self.root:
return self.search(self.root.right)
return self.search(self.root.left)
I tried storing self.search(self.root.right) and self.search(self.root.left) into variables and then returned them using or but still I get None as output.
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
class BinarySearchTree:
def __init__(self):
self.root = None
def search(self, key):
a = search(self.root)
if self.root is None or self.root == key:
return self.root
if key > self.root:
a = self.search(self.root.right)
b = self.search(self.root.left)
return a or b
I do not understand what I am doing wrong here and why the output is coming as None.
(I am a beginner and this is my first time asking a question here so please forgive me if I have made any silly mistake.)
This was my input
r = Node(1)
r.left = Node(2)
r.right = Node(3)
r.left.left = Node(4)
r.left.right = Node(5)
r.right.right = Node(6)
r.right.left = Node(7)
im using a FSM and have a Problem with a Key...
class SimpleFSM(object):
def __init__(self, char):
self.char = char
self.states = {}
self.transitions = {}
self.curState = None
self.trans = None
def SetState(self,stateName):
self.curState = self.states[stateName]
def Transition(self, transName):
self.trans = self.transitions[transName]
def Execute(self):
if(self.trans):
self.trans.Execute()
self.SetState(self.trans.toState)
self.trans = None
self.curState.Execute()
this is my init for the keys:
light.FSM.states["On"] = LightOn()
light.FSM.states["Off"] = LightOff()
light.FSM.transitions["toOn"] = Transition("On")
light.FSM.transitions["toOff"] = Transition("Off")
i can change the state if i use:
light.FSM.Transition("toOff")
but why it doesnt work if i use a String with "toOff" ?
lightOn = "toOff"
light.FSM.Transition(lightOn)
sry im a rookie and not much experience with Python.
I am trying to do an N-Ary tree based on Linked-Lists and Nodes. But whenever I try to add a new value to the tree I keep getting:
NameError: name 'self' is not defined
I work with modules so I have to import the classes from other files.
I get this error in def addTree(self, value, parent = self.root): on Tree Code
Tree Code
from Resources.LinkedList import *
class Tree:
def __init__(self):
self.root = LinkedList()
def addTree(self, value, parent = self.root):
parent.addLinkedList(value)
Node Code
from Resources.LinkedList import *
class Node:
def __init__(self,name):
self.name = name
self.children = LinkedList()
self.next = None
Linked-List Code
from Resources.Node import *
from Resources.Compare import *
class LinkedList:
def __init__(self):
self.first = None
def addLinkedList(self,value):
if (not self.first):
self.first = Node(value)
else:
compare = Compare()
if(compare.compare(self.first,value)>0):
stack = self.first
self.first = Node(value)
self.first.next = stack
return True
else:
previous = self.first
current = self.first.next
while(current):
if (compare.compare(current,value)<0):
previous = current
current = current.next
return True
elif (compare.compare(current,value)>0):
stack = current
previous.next = Node(value)
previous.next.next = stack
return True
else:
previous.next = Node(value)
previous.next.next = current.next
return True
previous.next = Node(value)
return True
Also thanks for your help, I'm kinda new to Python and I don't know what I am doing wrong.
The problem is that "self" is only defined within the method and cannot be used in the arguments, the trick in these cases is to use None as an argument and make the verification:
def addTree(self, value, parent = None):
if parent is None:
parent = self.root
parent.addLinkedList(value)