how to solve the print string error on python eclipse - python

I am not sure why do i get this error from the console:
<<
print stirngp[state[i][j]]
^
SyntaxError: invalid syntax
<<
Furthermore it seems that the IDE put a red close on the following code line
line = raw_input("Enter:")
I am not sure what did i do wrong, the following code is as shown below
def isTerminal(state):
stateT = zip(*state)
for i in range(3):
if all(state[i][0] == j for j in state[i]) and state[i][0] != 0:
return state[i][0]
if all(stateT[i][0] == j for j in stateT[i]) and stateT[i][0] != 0:
return stateT[i][0]
if (state[0][0] == state[1][1] == state[2][2]) or \
(state[0][2] == state[1][1] == state[2][0]):
if state[1][1] != 0:
return state[1][1]
for i in range(3):
if 0 in state[i]:
return None
return 0
def succ(state):
# print state
countX = 0
countO = 0
for i in range(3):
for j in range(3):
if state[i][j] == 1: countX = countX + 1
if state[i][j] == -1: countO = countO + 1
if countX > countO:
player = "MIN"
else:
player = "MAX"
succList = []
v = {"MIN":-1,"MAX":1}
for i in range(3):
for j in range(3):
if state[i][j] == 0:
succ = [k[:] for k in state]
succ[i][j] = v[player]
succList = succList + [succ]
# print succList
return succList
def nextplay(player):
if player == "MIN":
return "MAX"
else:
return "MIN"
def minimax(state,alpha,beta,player):
value = isTerminal(state)
if value != None:
# print "TERMINAL:", state, value, player
return value
if player == "MIN":
for y in succ(state):
beta = min(beta, minimax(y,alpha,beta,"MAX"))
if beta <= alpha: return alpha
return beta
if player == "MAX":
for y in succ(state):
alpha = max(alpha, minimax(y,alpha,beta,"MIN"))
if alpha >= beta: return beta
return alpha
def printing(state):
p = {-1:"O",0:".",1:"X"}
for i in range(3):
for j in range(3):
print p[state[i][j]],
print ""
print ""
def main():
state = [[0,0,0],
[0,0,0],
[0,0,0]]
val = isTerminal(state)
while val == None:
line = raw_input("Enter:")
x = line.split(",")
a = int(x[0]); b = int(x[1])
state[a][b] = 1
if isTerminal(state) != None:
printing(state)
return
# determine which successive state is better
succList = succ(state)
succValList = []
for i in succList:
succValList = succValList + [(minimax(i,-1,1,"MAX"),i)]
succValList.sort(key=lambda x:x[0])
state = succValList[0][1] # can also randomly choose other states of the same minimax value
printing(state)
val = isTerminal(state)
if __name__ == '__main__':
main()

As far as i know you can't use raw_input() in Python 3. It's been changed to just input()
http://docs.python.org/dev/whatsnew/3.0.html
also what is stringp? is it an existing list?
if so then state[i][j] MUST return an integer so you can retrieve the item at that index of stringp[]

Related

Connect 4 Python 3 - Declaring Global variables

I was programming a simple Connect 4 game however I need to add global variables
# Board(0:6, 0:7) : str (but ignore row 0 and column
0)
# ThisPlayer : str[1]
# GameFinished, WinnerFound : bool
# ColumnNumber : int
# ValidColumn, ValidRow : int
which im stuck on as I cant remember how to define global booleans etc (global variables are above)
when I run the code it gives me the error code (Board is not defined) how can I add the global variables so my program runs ?
Code is below
Board[0:6][0:7]
Blank = '.'
def InititialiseBoard():
Board = [[Blank for i in range(7)]
for j in range(6)]
def SetUpGame():
ThisPlayer = 'o'
GameFinished = False
def OutputBoard():
for Row in range(6 , 0 , -1):
for Column in range(7):
print(Board[Row][Column] , end = '')
print()
def ColumnNumberValud():
Valid = False
if ColumnNumber >= 1 and CalumnNumber <= 7:
if Board[6][ColumnNumber] == Blank:
Valid = True
return Valid
def ThisPlayerChoosesColumn():
print('Player ' + ThisPlayer + ' turn.')
while ColumnNumberValid == False:
print('Enter Valid Column Number')
ColumnNumber = int(input('Enter Column Number: '))
return ColumnNumber
def ThisPlayerMakesMove():
ValidColumn = ThisPlayerChoosesColumn()
ValidRow = FindNextFreePositionInColumn()
Board[ValidRow][ValidColumn] = ThisPlayer
def FindNextFreePositionInColumn():
ThisRow = 1
while Board[ThisRow][ValidColumn] != Blank:
ThisRow = ThisRow + 1
return ThisRow
def CheckHorizontalLineInValidRow():
for i in range(4):
if Board[ValidRow][i] == ThisPlayer and Board[ValidRow][i+1] == ThisPlayer and Board[ValidRow][i+2] == ThisPlayer and Board[ValidRow][i+3] == ThisPlayer:
WinnerFound = True
def CheckVerticalLineInValidRow():
if ValidRow == 4 or ValidRow == 5 or ValidRow == 6:
if Board[ValidRow][ValidColumn] == ThisPlayer and Board[ValidRow - 1][ValidColumn] == ThisPlayer and Board[ValidRow - 2][ValidColumn] == ThisPlayer and Board[ValidRow - 3 ][ValidColumn] == ThisPlayer:
WinnerFound = True
def CheckForFullBoard():
BlankFound = False
ThisRow = 0
while ThisRow !=6 or BlankFound == False:
ThisColumn = 0
ThisRow = ThisRow + 1
while ThisColumn != 7 or BlankFound == True:
ThisColumn = ThisColumn + 1
if Board[ThisRow][ThisColumn] == Blank:
BlankFound = True
if Blankfound == False:
print('Draw')
GameFinished = True
def CheckIfThisPlayerHasWon():
WinnerFound = False
CheckHorizontalLineInValidRow()
if WinnerFound == False:
CheckVerticalLineInValidColumn()
if WinnerFound == True:
GameFinished = True
print(ThisPlayer , 'Winner')
else:
CheckForFullBoard()
To use global variables:
global x
x = 1
def foo():
global x
x+=1
print(x)
foo()
print(x)
I would recommend avoiding global variables and use class variables instead.
class yourclass():
def__init__(self):
self.x = 1
def foo(self):
self.x+=1
def print_value(self):
print(self.x)
if __name__=='__main__':
test = yourclass()
test.print_value()
test.foo()
test.print_value()

Implementing Knuth-Morris-Pratt (KMP) algorithm for string matching with Python

I am following Cormen Leiserson Rivest Stein (clrs) book and came across "kmp algorithm" for string matching. I implemented it using Python (as-is).
However, it doesn't seem to work for some reason. where is my fault?
The code is given below:
def kmp_matcher(t,p):
n=len(t)
m=len(p)
# pi=[0]*n;
pi = compute_prefix_function(p)
q=-1
for i in range(n):
while(q>0 and p[q]!=t[i]):
q=pi[q]
if(p[q]==t[i]):
q=q+1
if(q==m):
print "pattern occurs with shift "+str(i-m)
q=pi[q]
def compute_prefix_function(p):
m=len(p)
pi =range(m)
pi[1]=0
k=0
for q in range(2,m):
while(k>0 and p[k]!=p[q]):
k=pi[k]
if(p[k]==p[q]):
k=k+1
pi[q]=k
return pi
t = 'brownfoxlazydog'
p = 'lazy'
kmp_matcher(t,p)
This is a class I wrote based on CLRs KMP algorithm, which contains what you are after. Note that only DNA "characters" are accepted here.
class KmpMatcher(object):
def __init__(self, pattern, string, stringName):
self.motif = pattern.upper()
self.seq = string.upper()
self.header = stringName
self.prefix = []
self.validBases = ['A', 'T', 'G', 'C', 'N']
#Matches the motif pattern against itself.
def computePrefix(self):
#Initialize prefix array
self.fillPrefixList()
k = 0
for pos in range(1, len(self.motif)):
#Check valid nt
if(self.motif[pos] not in self.validBases):
self.invalidMotif()
#Unique base in motif
while(k > 0 and self.motif[k] != self.motif[pos]):
k = self.prefix[k]
#repeat in motif
if(self.motif[k] == self.motif[pos]):
k += 1
self.prefix[pos] = k
#Initialize the prefix list and set first element to 0
def fillPrefixList(self):
self.prefix = [None] * len(self.motif)
self.prefix[0] = 0
#An implementation of the Knuth-Morris-Pratt algorithm for linear time string matching
def kmpSearch(self):
#Compute prefix array
self.computePrefix()
#Number of characters matched
match = 0
found = False
for pos in range(0, len(self.seq)):
#Check valid nt
if(self.seq[pos] not in self.validBases):
self.invalidSequence()
#Next character is not a match
while(match > 0 and self.motif[match] != self.seq[pos]):
match = self.prefix[match-1]
#A character match has been found
if(self.motif[match] == self.seq[pos]):
match += 1
#Motif found
if(match == len(self.motif)):
print(self.header)
print("Match found at position: " + str(pos-match+2) + ':' + str(pos+1))
found = True
match = self.prefix[match-1]
if(found == False):
print("Sorry '" + self.motif + "'" + " was not found in " + str(self.header))
#An invalid character in the motif message to the user
def invalidMotif(self):
print("Error: motif contains invalid DNA nucleotides")
exit()
#An invalid character in the sequence message to the user
def invalidSequence(self):
print("Error: " + str(self.header) + "sequence contains invalid DNA nucleotides")
exit()
You might want to try out my code:
def recursive_find_match(i, j, pattern, pattern_track):
if pattern[i] == pattern[j]:
pattern_track.append(i+1)
return {"append":pattern_track, "i": i+1, "j": j+1}
elif pattern[i] != pattern[j] and i == 0:
pattern_track.append(i)
return {"append":pattern_track, "i": i, "j": j+1}
else:
i = pattern_track[i-1]
return recursive_find_match(i, j, pattern, pattern_track)
def kmp(str_, pattern):
len_str = len(str_)
len_pattern = len(pattern)
pattern_track = []
if len_pattern == 0:
return
elif len_pattern == 1:
pattern_track = [0]
else:
pattern_track = [0]
i = 0
j = 1
while j < len_pattern:
data = recursive_find_match(i, j, pattern, pattern_track)
i = data["i"]
j = data["j"]
pattern_track = data["append"]
index_str = 0
index_pattern = 0
match_from = -1
while index_str < len_str:
if index_pattern == len_pattern:
break
if str_[index_str] == pattern[index_pattern]:
if index_pattern == 0:
match_from = index_str
index_pattern += 1
index_str += 1
else:
if index_pattern == 0:
index_str += 1
else:
index_pattern = pattern_track[index_pattern-1]
match_from = index_str - index_pattern
Try this:
def kmp_matcher(t, d):
n=len(t)
m=len(d)
pi = compute_prefix_function(d)
q = 0
i = 0
while i < n:
if d[q]==t[i]:
q=q+1
i = i + 1
else:
if q != 0:
q = pi[q-1]
else:
i = i + 1
if q == m:
print "pattern occurs with shift "+str(i-q)
q = pi[q-1]
def compute_prefix_function(p):
m=len(p)
pi =range(m)
k=1
l = 0
while k < m:
if p[k] <= p[l]:
l = l + 1
pi[k] = l
k = k + 1
else:
if l != 0:
l = pi[l-1]
else:
pi[k] = 0
k = k + 1
return pi
t = 'brownfoxlazydog'
p = 'lazy'
kmp_matcher(t, p)
KMP stands for Knuth-Morris-Pratt it is a linear time string-matching algorithm.
Note that in python, the string is ZERO BASED, (while in the book the string starts with index 1).
So we can workaround this by inserting an empty space at the beginning of both strings.
This causes four facts:
The len of both text and pattern is augmented by 1, so in the loop range, we do NOT have to insert the +1 to the right interval. (note that in python the last step is excluded);
To avoid accesses out of range, you have to check the values of k+1 and q+1 BEFORE to give them as index to arrays;
Since the length of m is augmented by 1, in kmp_matcher, before to print the response, you have to check this instead: q==m-1;
For the same reason, to calculate the correct shift you have to compute this instead: i-(m-1)
so the correct code, based on your original question, and considering the starting code from Cormen, as you have requested, would be the following:
(note : I have inserted a matching pattern inside, and some debug text that helped me to find logical errors):
def compute_prefix_function(P):
m = len(P)
pi = [None] * m
pi[1] = 0
k = 0
for q in range(2, m):
print ("q=", q, "\n")
print ("k=", k, "\n")
if ((k+1) < m):
while (k > 0 and P[k+1] != P[q]):
print ("entered while: \n")
print ("k: ", k, "\tP[k+1]: ", P[k+1], "\tq: ", q, "\tP[q]: ", P[q])
k = pi[k]
if P[k+1] == P[q]:
k = k+1
print ("Entered if: \n")
print ("k: ", k, "\tP[k]: ", P[k], "\tq: ", q, "\tP[q]: ", P[q])
pi[q] = k
print ("Outside while or if: \n")
print ("pi[", q, "] = ", k, "\n")
print ("---next---")
print ("---end for---")
return pi
def kmp_matcher(T, P):
n = len(T)
m = len(P)
pi = compute_prefix_function(P)
q = 0
for i in range(1, n):
print ("i=", i, "\n")
print ("q=", q, "\n")
print ("m=", m, "\n")
if ((q+1) < m):
while (q > 0 and P[q+1] != T[i]):
q = pi[q]
if P[q+1] == T[i]:
q = q+1
if q == m-1:
print ("Pattern occurs with shift", i-(m-1))
q = pi[q]
print("---next---")
print("---end for---")
txt = " bacbababaabcbab"
ptn = " ababaab"
kmp_matcher(txt, ptn)
(so this would be the correct accepted answer...)
hope that it helps.

TypeError: 'NoneType' object is not iterable when implementing Perceptron, see code below

I have a problem with my perceptron codes.I receive this when I execute my code. I checked my two txt files and I am pretty sure the two of them are definitely ok. So can someone help? Thanks a lot
Traceback (most recent call last):
File "perceptron.py", line 160, in <module>
test()
File "perceptron.py", line 133, in test
w,k,i = p.perceptron_train('train.txt')
TypeError: 'NoneType' object is not iterable
Here is my code
import numpy as np
import matplotlib.pyplot as plt
class Data():
def __init__(self,x,y):
self.len = len(x)
self.x = x
self.y = y
class Perceptron():
def __init__(self,N,X):
self.w = np.array([])
self.N = N
self.X =X
def prepare_training(self,file):
file = open(file,'r').readlines()
self.dic = set([])
y = []
vocab = {}
for i in range(len(file)):
words = file[i].strip().split()
y.append(int(words[0])*2-1)
for w in set(words[1:]):
if w in vocab:
vocab[w].add(i)
if i < self.N and len(vocab[w]) >= self.X:
self.dic.add(w)
elif i < self.N:
vocab[w] = set([i])
x = np.zeros((len(file),len(self.dic)))
self.dic = list(self.dic)
for i in range(len(self.dic)):
for j in vocab[self.dic[i]]:
x[j][i] = 1
self.training = Data(x[:self.N],y[:self.N])
self.validation = Data(x[self.N:],y[self.N:])
return x,y
def update_weight(self,x,y):
self.w = self.w + x * y
def perceptron_train(self,data):
x,y = self.prepare_training(data)
self.w = np.zeros(len(self.dic),int)
passes = 0
total_passes = 100
k = 0
while passes < total_passes:
print('passes:',passes)
mistake = 0
for i in range(self.N):
check = y[i] * np.dot(self.w,x[i])
if (check == 0 and (not
np.array_equal(x[i],np.zeros(len(self.dic),int)))) or (check < 0):
self.update_weight(x[i],y[i])
mistake += 1
k += 1
passes += 1
print('mistake:',mistake)
if mistake == 0:
print('converge at pass:',passes)
print('total mistakes:', k)
return self.w, k, passes
def perceptron_error(self,w,data):
error = 0
for i in range(data.len):
if data.y[i] * np.dot(w,data.x[i]) < 0:
error += 1
return error/data.len
def test(self,report):
x = np.zeros(len(self.dic),int)
for i in range(len(self.dic)):
if self.dic[i] in report:
x[i] = 1
if np.dot(self.w,x) > 0:
return 1
else:
return 0
def perceptron_test(self,data):
test = open(data,'r').readlines()
y = []
mistake = 0
for t in test:
y0 = int(t.strip().split()[0])
report = set(t.strip().split()[1:])
r = self.test(report)
y.append(r)
if (y0 != r):
mistake += 1
return y,mistake/len(test)
def predictive_words(self):
w2d = {}
for i in range(len(self.dic)):
try:
w2d[self.w[i]].append(self.dic[i] + " ")
except:
w2d[self.w[i]] = [self.dic[i] + " "]
key = list(w2d.keys())
key.sort()
count = 0
most_positive = ""
most_negative = ""
for i in range(len(key)):
for j in range(len(w2d[key[i]])):
most_negative += w2d[key[i]][j]
count += 1
if count == 5:
break
if count == 5:
break
count = 0
for i in range(len(key)):
for j in range(len(w2d[key[len(key)-i-1]])):
most_positive += w2d[key[len(key)-i-1]][j]
count += 1
if count == 5:
break
if count == 5:
break
return most_positive,most_negative
def test():
p = Perceptron(500,30)
w,k,i = p.perceptron_train('train.txt')
print(p.perceptron_error(w,p.validation))
normal,abnormal = p.predictive_words()
print('Normal:\n',normal)
print('Abnormal:\n',abnormal)
print(p.perceptron_test('test.txt'))
def plot_error():
x = [100,200,400,500]
y = []
for n in x:
p = Perceptron(n,10)
w,k,i = p.perceptron_train('train.txt')
y.append(p.perceptron_error(w,p.validation))
plt.plot(x,y)
plt.show()
def plot_converge():
x = [100,200,400,500]
y = []
for n in x:
p = Perceptron(n,10)
w,k,i = p.perceptron_train('train.txt')
y.append(i)
plt.plot(x,y)
plt.show()
test()
perceptron_train has the implicit return value None if mistakes!=0, so that's what you're seeing here.

Minimum spanning tree using Kruskal in Python, recursion enters a infinite loop

The purpose of this code is to create the shortest path that connect each point. I've tried to implement the Kruskals algorithm in Python, but there is a problem and it occurs when the function findSet(x) is called. It seems like the program enters a infinite loop. I've tried to print x, x.dad and x.dad.dad and x in the crucial moment returns the initial x. I really don't know where is the problem.
class Point:
def __init__(self,x = None, y = None):
self.x = x
self.y = y
self.dad = None
self.rank = None
class Edge:
def __init__(self, firstPoint = None, secondPoint = None, value = None):
self.firstPoint = firstPoint
self.secondPoint = secondPoint
if self.firstPoint != None and self.secondPoint != None:
self.value = abs(firstPoint.x-secondPoint.x) + abs(firstPoint.y - secondPoint.y)
else:
self.value = float("inf")
def makeSet(node):
node.dad = node
node.rank = 0
def findSet(x):
print x, x.dad,x.dad.dad
if x == x.dad:
return x
x.dad = findSet(x.dad)
return x.dad
def unionSet(node1,node2):
root1 = findSet(node1)
root2 = findSet(node2)
if root1.rank < root2.rank:
root1.dad = root2
if root1.rank > root2.rank:
root2.dad = root1
else:
root2.dad = root1
root1.rank += 1
def merge(A, p, q, r):
L = A[p:q+1]
R = A[q+1:r+1]
infinite = Edge()
L.append(infinite)
R.append(infinite)
temp = []
i = 0
j = 0
for k in range(p,r+1):
if L[i].value <= R[j].value:
temp.append(L[i])
i += 1
else:
temp.append(R[j])
j += 1
A[p:r+1] = temp
def mergeSort(A,p,r):
A2 = A
if p < r:
q = int((p+r)/2)
mergeSort(A2, p, q)
mergeSort(A2, q+1, r)
merge(A2, p, q, r)
def readPoint(A):
temp = []
for i in range(0,len(A), 2):
tempPoint = Point(A[i],A[i+1])
makeSet(tempPoint)
temp.append(tempPoint)
return temp
def calculateEdges(A):
tempArray = []
for i in range(0,len(A)):
for j in range(i+1,len(A)):
edge = Edge(A[i], A[j])
tempArray.append(edge)
return tempArray
def Kruskal(N, E):
mergeSort(E,0,len(E)-1)
j = 0
i = 0
total = 0
while j < N:
if findSet(E[i].firstPoint) != findSet(E[i].secondPoint):
unionSet(E[i].firstPoint,E[i].secondPoint)
j += 1
total += E[i].value
if i < len(E) - 1:
i += 1
return total
Ar = readPoint([18, 2, 99, 68])
E = calculateEdges(Ar)
print Kruskal(len(Ar),E)

I got stuck on Python error TypeError: unhashable type: 'slice'

from informedSearch import *
from search import *
class EightPuzzleProblem(InformedProblemState):
"""
Inherited from the InformedProblemState class. To solve
the eight puzzle problem.
"""
def __init__(self, myList, list = {}, operator = None):
self.myList = list
self.operator = operator
def __str__(self):
## Method returns a string representation of the state.
result = ""
if self.operator != None:
result += "Operator: " + self.operator + ""
result += " " + ' '.join(self.myList[0:3]) + "\n"
result += " " + ' '.join(self.myList[3:6]) + "\n"
result += " " + ' '.join(self.myList[6:9]) + "\n"
return result
def illegal(self):
## Tests whether the state is illegal.
if self.myList < 0 or self.myList > 9: return 1
return 0
def equals(self, state):
## Method to determine whether the state instance
## and the given state are equal.
return ' '.join(self.myList) == ' '.join(state.myList)
## The five methods below perform the tree traversing
def move(self, value):
nList = self.myList[:] # make copy of the current state
position = nList.index('P') # P acts as the key
val = nList.pop(position + value)
nList.insert(position + value, 'P')
nList.pop(position)
nList.insert(position, val)
return nList
def moveleft(self):
n = self.move(-1)
return EightPuzzleProblem(n, "moveleft")
def moveright(self):
n = self.move(1)
return EightPuzzleProblem(n, "moveright")
def moveup(self):
n = self.move(-3)
return EightPuzzleProblem(n, "moveup")
def movedown(self):
n = self.move(+3)
return EightPuzzleProblem(n, "movedown")
def operatorNames(self):
return ["moveleft", "moveright", "moveup", "movedown"]
def enqueue(self):
q = []
if (self.myList.index('P') != 0) and (self.myList.index('P') != 3) and (self.myList.index('P') != 6):
q.append(self.moveleft())
if (self.myList.index('P') != 2) and (self.myList.index('P') != 5) and (self.myList.index('P') != 8):
q.append(self.moveright())
if self.myList.index('P') >= 3:
q.append(self.moveup())
if self.myList.index('P') >= 5:
q.append(self.movedown())
def applyOperators(self):
return [self.moveleft(), self.moveright(), self.moveup(), self.movedown()]
def heuristic():
counter = 0
for i in range(len(self.myList)):
if ((self.myList[i] != goal.myList[i]) and self.myList[i] != 'P'):
## Position of current:
current = goal.myList.index(self.myList[i])
if current < 3: goalRow = 0
elif current < 6: goalRow = 1
else: goalRow = 2
if i < 3: initRow = 0
elif i < 6: initRow = 1
else: startRow = 2
initColumn = i % 3
goalColumn = current % 3
counter += (abs(goalColumn - initColumn) + abs(goalRow - initRow))
return counter
#Uncomment to test the starting states:
init = ['1','3','P','8','2','4','7','6','5'] #A
#init = ['1','3','4','8','6','2','P','7','5'] #B
#init = ['P','1','3','4','2','5','8','7','6'] #C
#init = ['7','1','2','8','P','3','6','5','4'] #D
#init = ['8','1','2','7','P','4','6','5','3'] #E
#init = ['2','6','3','4','P','5','1','8','7'] #F
#init = ['7','3','4','6','1','5','8','P','2'] #G
#init = ['7','4','5','6','P','3','8','1','2'] #H
goal = ['1','2','3','8','P','4','7','6','5'] #goal state
InformedSearch(EightPuzzleProblem(init), EightPuzzleProblem(goal))
I run it and it shows error
line 34, in __str__ result += " " + ' '.join(self.myList[0:3]) + "\n"
TypeError: unhashable type: 'slice'
Any Ideas?
You're setting the "list" to a dictionary as a default value: list = {} in:
def __init__(self, myList, list = {}, operator = None):
and then assigning it to myList with:
self.myList = list
A dictionary cannot be sliced like a list. So when you try to slice it:
self.myList[0:3]
it fails.

Categories

Resources