KeyError with a String Python - python

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.

Related

Why my code solve word error rate by breadth first search is doesn’t work?

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

Manipulate self object in class

i implement a linked list in Python for my student and particulary a simply version of the "reverse" method ...
This a version that works :
class SimpleList:
def __init__(self, *args):
if len(args) == 0:
self.__cell = None
elif len(args) == 2:
if isinstance(args[1], SimpleList):
self.__cell = (args[0], args[1])
else:
print("Erreur 2")
else:
print("Erreur 3")
def car(self):
if not self.isNull():
return self.__cell[0]
print("Erreur 4")
def cdr(self):
if not self.isNull():
return self.__cell[1]
print("Erreur 5")
def isNull(self):
return self.__cell == None
def __repr__(self):
if self.isNull():
return '()'
else:
return '(' + repr(self.car()) + ',' + repr(self.cdr()) + ')'
def nbrElement(self):
num = 0
tab = self
while not(tab.isNull()):
num = num+1
tab = tab.cdr()
return num
def reverse(self):
num=self.nbrElement()-1
pCourant = SimpleList(self.car(),SimpleList())
tab = self.cdr()
for i in range(0,num-1):
tabTmp = tab
tab = tab.cdr()
tabTmp.__cell = (tabTmp.car(),pCourant)
pCourant= tabTmp
self.__cell = neww = (tab.car(),pCourant)
and the code to execute :
slA = SimpleList(10,SimpleList(9,SimpleList(8,SimpleList(7,SimpleList(6,SimpleList(5,SimpleList(4,SimpleList())))))))
print(slA)
slA.reverse()
print(slA)
but i need to redefine the new tail object
I try to do it only with "swap" the inner link :
def reverse(self):
num=self.nbrElement()-1
pCourant = SimpleList()
tab = self
for i in range(0,num-1):
tabTmp = tab
tab = tab.cdr()
tabTmp.__cell = (tabTmp.car(),pCourant)
pCourant= tabTmp
self.__cell = neww = (tab.car(),pCourant)
There is a personn that can explain me this ???
Thanks for your help
Update :
def reverse(self):
num=self.nbrElement()-1
pCourant = SimpleList()
tab = self
for i in range(0,num):
tabTmp = tab
tab = tab.cdr()
tabTmp.__cell = (tabTmp.car(),pCourant)
pCourant= tabTmp
neww = SimpleList(tab.car(),pCourant)
print(neww)
print(neww)
self.__cell = neww.__cell
slA = SimpleList(10,SimpleList(9,SimpleList(8,SimpleList())))
slA.reverse()
print(slA.cdr().cdr().car())
print(slA)
Is notfor optimize my code ... But for understand, the "inner logic" of Python :
print(new) works well
a print(slA) do a "maximum recursion depth"
the penultimate display offer 8 but normally would display 10
Thanks for all
Since I'm still in the process of drinking my first cup of coffee, here's a simpler reimplementation.
(The __slots__ thing is a pre-optimization; you can elide it if you like.)
class ListCell:
__slots__ = ("value", "next")
def __init__(self, value, next=None):
self.value = value
self.next = next
def __repr__(self):
if not self.next:
return f"({self.value!r})"
else:
return f"({self.value!r},{self.next!r})"
def reverse(self):
prev = next = None
curr = self
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev # Return new head
#classmethod
def from_iterable(cls, items):
head = tail = None
for item in items:
if head is None:
head = tail = cls(item)
else:
tail.next = cls(item)
tail = tail.next
return head
lc = ListCell.from_iterable([1, 2, 4, 8])
print(lc)
lc = lc.reverse()
print(lc)
This prints out
(1,(2,(4,(8))))
(8,(4,(2,(1))))

Trie implementation in Python

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')

Print dict with custom class as values wont call their string method?

I was messing around with classes in python and wrote 2 little ones:
class ClaElement:
start = None
end = None
basesLeft = None
orientation = None
contig = None
size = None
def __init__(self, contig, start, end, orientation, basesLeft=None):
self.contig = contig
self.start = start
self.end = end
self.orientation = orientation
self.basesLeft = basesLeft
self.size = self.end - self.start
def __str__(self):
return "{ClaElement: "+str(self.contig)+"_"+str(self.start)+"_"+str(self.end)+"_"+str(self.orientation)+"}"
def getSize(self):
return self.size
class ClaCluster:
contig = None
clusterElements = []
def __init__(self, contig, firstElement):
self.contig = contig
self.addElement(firstElement)
def addElement(self, claElement):
self.clusterElements.append(claElement)
def getFirst(self):
return self.clusterElements[0]
def getLast(self):
return self.clusterElements[-1]
def getElements(self):
return self.clusterElements
def getContig(self):
return self.contig
def __str__(self):
return "{ClaCluster: "+str(self.contig)+" "+str(len(self.clusterElements))+" elements}"
And my test-main:
from ClaElement import ClaElement
from ClaCluster import ClaCluster
if __name__ == '__main__':
ele = ClaElement("x",1,2,"left")
claDict = dict()
cluster = ClaCluster("x", ele)
claDict["hello"] = cluster
print(claDict)
print(claDict["hello"])
print(ele)
This leads to the following output:
{'hello': <ClaCluster.ClaCluster object at 0x7fe8ee04c5f8>}
{ClaCluster: x 1 elements}
{ClaElement: x_1_2_left}
Now my question is why is the output of my first print the memory address even though I provided a functioning string-method for my class ClaCluster? Is there a way to get the method invoked when I am printing the dictionary or do I have to iterate by hand?
The __str__() method of the built-in dict type uses the __repr__() method of your class, not __str__(). Simply rename your method, and all should work fine.

Python variable is not getting initialized with desired object, why?

So I am designing a battleship backend system that will be running on google apps engine... I just started yesterday and designed a framework for the game.
Unfortunately for me, I have not coded too much in python so I am not too familiar with the specifics of the language. I keep getting the following error when I try to run the program:
File "C:\Users\Shlomo\Desktop\eclipse\plugins\org.python.pydev_2.7.5.2013052819\pysrc\pydev_runfiles.py", line 432, in __get_module_from_str
mod = __import__(modname)
File "C:\Users\Shlomo\workspace\battleship\Battleship.py", line 222, in <module>
battleship = BattleshipGame("Shlomo",1,1,4,1,1,2,5,2,1,3,3,3,1,4,2,4,1,5,5,5,"John",1,1,4,1,1,2,5,2,1,3,3,3,1,4,2,4,1,5,5,5)
File "C:\Users\Shlomo\workspace\battleship\Battleship.py", line 210, in __init__
field = self.player1_field.getField()
AttributeError: 'NoneType' object has no attribute 'getField'
ERROR: Module: Battleship could not be imported (file: C:\Users\Shlomo\workspace\battleship\Battleship.py).
So I translated this error as the variable field is not getting initialized with the PlayerField object...
Here is my code:
import random
class Player:
player_name = None
player_id = None
game_id = None
your_turn = False
player_field = None
hit_field = None
opponent = None
def __init__(self,name,player_field,hit_field,opponent):
self.player_name = name
self.player_field = player_field
self.hit_field = hit_field
self.opponent = opponent
def getPlayerField(self):
return self.player_field
def performHit(self,x,y):
mark = None
hit = self.opponent.getPlayerField.hitAt(x,y)
if hit:
mark = 'X'
else:
mark = 'O'
self.hit_field.markHitField(x,y,mark)
class HitField:
hit_field = None
def __init__(self):
hit_field = [[0 for i in xrange(10)] for i in xrange(10)]
def markHitField(self,x,y,mark):
self.hitfield[x][y] = mark
class PlayerField:
player_field = [[0 for i in xrange(10)] for i in xrange(10)]
shipsOnField = []
goodToGo = False
def __init__(self,battleship,aircraft,destroyer,submarine,patrol):
if self.validPlacement(battleship)and self.validPlacement(aircraft)and self.validPlacement(destroyer) and self.validPlacement(submarine) and self.validPlacement(patrol):
self.placeShip(battleship)
self.placeShip(aircraft)
self.placeShip(destroyer)
self.placeShip(submarine)
self.placeShip(patrol)
self.shipsOnField.append(battleship)
self.shipsOnField.append(aircraft)
self.shipsOnField.append(destroyer)
self.shipsOnField.append(submarine)
self.shipsOnField.append(patrol)
self.goodToGo = True
else:
print "some pieces have been placed incorrectly"
def validPlacement(self,ship):
hx = ship.getHeadX;
hy = ship.getHeadY;
tx = ship.getTailX;
ty = ship.getTailY;
if not hx > 0 and not hx < 11:
return False
return True
def placeShip(self,ship):
hx = ship.getHeadX();
hy = ship.getHeadY();
tx = ship.getTailX();
ty = ship.getTailY();
for y in range(ty,hy):
for x in range(tx,hx):
self.player_field[x][y] = ship.getShipID
def hitAt(self,x,y):
hitPos = self.player_field[x][y]
if not hitPos == 0 and not hitPos == 'X':
self.getShipByID(hitPos).removeHealth
self.player_field[x][y] = 'X'
return True
def getShipByID(self,ID):
for ship in self.shipsOnField:
if ship.getShipID == ID:
return ship
def getField(self):
return self.player_field
class Ship(object):
ship_id = None
ship_name = None
max_health = None
remaining_health = None
head_pos_x = None
head_pos_y = None
tail_pos_x = None
tail_pos_y = None
def __init__(self,id,name,max,hx,hy,tx,ty):
self.ship_id = id
self.max_health = max
self.remaining_health = max
self.ship_name = name
self.head_pos_x = hx
self.head_pos_y = hy
self.tail_pos_x = tx
self.tail_pos_y = ty
self.remaining_health = max
def removeHealth(self):
self.remaining_health -= 1
def getHeadX(self):
return self.head_pos_x
def getHeadY(self):
return self.head_pos_y
def getTailX(self):
return self.tail_pos_x
def getTailY(self):
return self.tail_pos_y
def getRemainingHealth(self):
return self.remaining_health
def getShipID(self):
return self.ship_id
class Battleship(Ship):
def __init__(self,hx,hy,tx,ty):
Ship.__init__(self,1,"Battle Ship",4,hx,hy,tx,ty)
class AircraftCarrier(Ship):
def __init__(self,hx,hy,tx,ty):
Ship.__init__(self,2,"Aircraft Carrier",5,hx,hy,tx,ty)
class Destroyer(Ship):
def __init__(self,hx,hy,tx,ty):
Ship.__init__(self,3,"Destroyer",3,hx,hy,tx,ty)
class Submarine(Ship):
def __init__(self,hx,hy,tx,ty):
Ship.__init__(self,4,"Submarine",3,hx,hy,tx,ty)
class PatrolBoat(Ship):
def __init__(self,hx,hy,tx,ty):
Ship.__init__(self,5,"Patrol Boat",2,hx,hy,tx,ty)
class BattleshipGame:
current_turn = None
player1 = None
player2 = None
player1_field = None
player1_opponent = player2
player2_field = None
player2_opponent = player1
def firstTurn(self):
rand = random.randint(1,2)
if rand==1:
return self.player1
else:
return self.player2
def printGameBoard(self):
field = self.player1_field.getField()
for y in range(1,10):
for x in range(1,10):
print field[x][y]
print '\n'
def __init__(self,p1name,p1bshx,p1bshy,p1bstx,p1bsty
,p1dhx,p1dhy,p1dtx,p1dty
,p1shx,p1shy,p1stx,p1sty
,p1pbhx,p1pbhy,p1pbtx,p1pbty
,p1achx,p1achy,p1actx,p1acty
,p2name,p2bshx,p2bshy,p2bstx,p2bsty
,p2dhx,p2dhy,p2dtx,p2dty
,p2shx,p2shy,p2stx,p2sty
,p2pbhx,p2pbhy,p2pbtx,p2pbty
,p2achx,p2achy,p2actx,p2acty):
player1_field = PlayerField(Battleship(p1bshx,p1bshy,p1bstx,p1bsty),
AircraftCarrier(p1achx,p1achy,p1actx,p1acty),
Destroyer(p1dhx,p1dhy,p1dtx,p1dty),
Submarine(p1shx,p1shy,p1stx,p1sty),
PatrolBoat(p1pbhx,p1pbhy,p1pbtx,p1pbty))
player2_field = PlayerField(Battleship(p2bshx,p2bshy,p2bstx,p2bsty),
AircraftCarrier(p2achx,p2achy,p2actx,p2acty),
Destroyer(p2dhx,p2dhy,p2dtx,p2dty),
Submarine(p2shx,p2shy,p2stx,p2sty),
PatrolBoat(p2pbhx,p2pbhy,p2pbtx,p2pbty))
player1 = Player(p1name,self.player1_field,HitField(),self.player2)
player2 = Player(p2name,self.player2_field,HitField(),self.player1)
self.current_turn = self.firstTurn()
battleship = BattleshipGame("Player1",1,1,4,1,1,2,5,2,1,3,3,3,1,4,2,4,1,5,5,5,"Player2",1,1,4,1,1,2,5,2,1,3,3,3,1,4,2,4,1,5,5,5)
battleship.printGameBoard()
Sorry about the sytax, I had trouble pasting it in the code format. This code probably has a few problems but I have not been able to get passed this problem yet...
What am I doing wrong?
In your __init__, you're assigning to a local variable player1_field rather than to instance data. Instead of:
player1_field = PlayerField(...
You want:
self.player1_field = PlayerField(...
Without that, you're trying to deference your class's value for player1_field, which is None.
Python isn't Java or whatever language you are trying to write. These mutable class attributes are unlikely to do what you think they do.
class PlayerField:
player_field = [[0 for i in xrange(10)] for i in xrange(10)]
shipsOnField = []
goodToGo = False

Categories

Resources