Related
data = input("Input:")
def parse_to_int(dat): # parse input data to int list
individuals = dat.split(" ")
num = []
for individual in individuals:
num.append((int)(individual))
return num
def get_Max_and_MaxIndex_MinIndex(num_list): # get maximul value, its index and minimum value
sign = 1
val = 0
max_val = 0
min_val = 0
max_ind = 0
count = 0
for num in num_list:
count += 1
val = val + sign * num
sign = -1 * sign
if (max_val < val):
max_val = val
max_ind = count
if (min_val > val):
min_val = val
return max_val, max_ind, min_val
def sub_sum(ind): # calculate subsum until ind
global num_input
global subsum
subsum = 0
for i in range(ind + 1):
subsum += num_input[i]
return subsum
def sub_sum_with_sign(ind): # calculate subsum with sign until ind
global num_input
global subsum_withsign
subsum_withsign = 0
sign = 1
for i in range(ind + 1):
subsum_withsign += sign * num_input[i]
sign = -1 * sign
return subsum_withsign
def fill_data(ind): # fill data for print in empty data
global print_data
global cur_x
global cur_y
if ind % 2 == 0:
str = '/'
dx = 1
dy = 1
else:
str = '\\'
dx = 1
dy = -1
for _ in range(num_input[ind]):
print_data[cur_y][cur_x] = str
cur_x += dx
cur_y += dy
if ind % 2 == 0:
cur_y -= 1
else:
cur_y += 1
return print_data
# main program
num_input = parse_to_int(data)
col_num = 0 # column count
for elem in num_input:
col_num += elem
max_min_num = get_Max_and_MaxIndex_MinIndex(num_input)
row_num = max_min_num[0] - max_min_num[2] # row count
start_num = 0
for i in range(max_min_num[1]):
start_num += num_input[i] # maximum height element number
subsum = 0
subsum_withsign = 0
cur_x = 0
cur_y = -1 * max_min_num[2]
# start output
print("Output:\n")
print(" " * start_num + "o" + " " * (col_num - start_num))
print(" " * (start_num - 1) + "/|\\" + " " * (col_num - start_num - 1))
print(" " * (start_num - 1) + "< >" + " " * (col_num - start_num - 1))
# prepare data for print
print_data = []
for i in range(row_num):
print_data.append([])
for j in range(col_num):
print_data[i].append(" ")
for ind in range(len(num_input)):
fill_data(ind)
# print data
for indr in range(row_num - 1, -1, -1):
print("".join(print_data[indr]))
The above code will give this Output
In this code, a graph is generated using python without using any libraries. The Highest tip of the graph is marked.
I want to mark the lowest tip of the graph as shown in the image below. I completely have no idea about this one. which values should be changed in order to mark the lowest tip in the generated graph?
I am a newbie to stackoverflow, please comment if you need more clarity with this..
How to mark the lowest tip here Please Help me with this
My friend and I wrote the following code to solve partial differential equations:
import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse as sp
import scipy.sparse.linalg as la
import gc
import time
#%%
h = 0.1
const = 1
dt1 = 0.25*0.99*h**2
dt2 = 0.1
dt3 = 0.001
Nt_1 = int(40.0/dt1+1)
Nt_2 = int(40.0/dt2+1)
Nt_3 = int(40.0/dt3+1)
t_1 = np.linspace(0,40.0,Nt_1)
t_2 = np.linspace(0,40.0,Nt_2)
t_3 = np.linspace(0,40.0,Nt_3)
xbegin = 0
xend = 16
ybegin = 0
yend = 8
Sx = xend-xbegin
Sy = yend-xbegin
Nx = int(Sx/h+1)
Ny = int(Sy/h+1)
Np = (Nx-2)*(Ny-2)
I = sp.eye(Np,Np,format='csc')
def meshcreator(xb,xe,yb,ye):
meshy1,meshx1 = np.mgrid[yb+h:ye:h,xb+h:xe:h]
return meshy1,meshx1
def Matrixmaker(Nx3,Ny3):
Dx = 1/h*(sp.diags([-1, 1], [-1, 0], shape=(Nx3-1, Nx3-2),format='csc'))
Dy = 1/h*(sp.diags([-1, 1], [-1, 0], shape=(Ny3-1, Ny3-2),format='csc'))
Dx_t = Dx.transpose()
Dy_t = Dy.transpose()
Lxx = Dx_t.dot(Dx)
Lyy = Dy_t.dot(Dy)
Ix = sp.eye(Nx3-2)
Iy = sp.eye(Ny3-2)
L = sp.kron(Iy,Lxx) + sp.kron(Lyy,Ix)
L = -L
return L
#%%
def k_maker(h1,Nx1,Ny1,q):
meshy2,meshx2 = meshcreator(xbegin,xend,ybegin,yend)
# k1 = sp.lil_matrix((Ny1-2, Nx1-2)).toarray()
k1 = np.zeros((Ny1-2,Nx1-2))
for i in range(len(meshx2[:,0])):
for j in range(len(meshx2[0,:])):
if 1 <= meshx2[i,j] <= 2 and 1 <= meshy2[i,j] <= 2:
k1[i,j] = q
elif 1 <= meshx2[i,j] <= 3 and 3 <= meshy2[i,j] <= 5:
k1[i,j] = q
elif 4 <= meshx2[i,j] <= 7 and 4 <= meshy2[i,j] <= 7:
k1[i,j] = q
elif 9 <= meshx2[i,j] <= 12 and 4 <= meshy2[i,j] <= 6:
k1[i,j] = q
elif 13 <= meshx2[i,j] <= 15 and 1 <= meshy2[i,j] <= 3:
k1[i,j] = q
return k1, meshx2, meshy2
k,meshx,meshy = k_maker(h,Nx,Ny,const)
plt.figure(4)
plt.spy(k,aspect='equal')
k = k.reshape((Np,1))
#%%
def ut0(x,y):
return (np.exp(-2*(x-1.5)**2-2*(y-1.5)**2).reshape(Np))
def jacobian(L2,value):
value2 = k*value
u_diag = sp.diags(diagonals = [np.reshape(value2,(Np))],offsets=[0],shape=(Np,Np),format='csc')
jacob = L2 + sp.diags(diagonals = [k.reshape(Np)],offsets=[0],shape=(Np,Np),format='csc') - 2*u_diag
return jacob
#%%
A = Matrixmaker(Nx,Ny)
ut0 = (ut0(meshx,meshy).reshape(Np,1))
def FE_BE_iterator(L3,u1,u0,timestep,Nt,choice,t,eps1 = 10e-3):
def f1(uk):
return L3*uk
def f2(uk):
return k*uk
def f3(uk):
utmp = uk*uk
return k*utmp
def F0(uk):
return f1(uk)+f2(uk)-f3(uk)
errorlist = []
usollist = [u0]
count = 0
if choice == 'Forward':
timerstart = time.time()
for i in range(Nt):
usol = timestep*(F0(u0))+u0
u0 = usol
if abs(t[i]-1) <= timestep and count == 0:
usollist.append(usol.reshape(Np,1))
count +=1
if abs(t[i]-2) <= timestep and count == 1:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-3) <= timestep and count == 2:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-5) <= timestep and count == 3:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-10) <= timestep and count == 4:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-20) <= timestep and count == 5:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-40) <= timestep and count == 6:
usollist.append(usol.reshape(Np,1))
count+=1
timerend = time.time()
time_elapsed = timerend-timerstart
print("Time elapsed for " + choice + " = ", time_elapsed)
return usollist,errorlist
if choice == 'Newton':
timerstart = time.time()
for i in range(Nt):
residual = 1
while residual > eps1:
jac = jacobian(L3,u1)
S = I-jac*timestep
RHS = u1-u0-timestep*F0(u1)
v = (la.spsolve(S,RHS)).reshape(Np,1)
ukp1 = u1-v
u1 = ukp1
residual = np.linalg.norm(v)
errorlist.append(residual)
usol = timestep*(F0(ukp1)) + u0
u0 = usol
if abs(t[i]-1) <= timestep and count == 0:
usollist.append(usol.reshape(Np,1))
count +=1
if abs(t[i]-2) <= timestep and count == 1:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-3) <= timestep and count == 2:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-5) <= timestep and count == 3:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-10) <= timestep and count == 4:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-20) <= timestep and count == 5:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-40) <= timestep and count == 6:
usollist.append(usol.reshape(Np,1))
count+=1
timerend = time.time()
time_elapsed = timerend-timerstart
print("Time elapsed for " + choice + " = ", time_elapsed)
return usollist,errorlist
if choice == 'Picard':
timerstart = time.time()
for i in range(Nt):
usol = u0
residual = 1
while residual > eps1:
usol = timestep*F0(usol) + u0
residual = np.linalg.norm(usol-timestep*F0(usol)-u0)
u0 = usol
if abs(t[i]-1) <= timestep and count == 0:
usollist.append(usol.reshape(Np,1))
count +=1
if abs(t[i]-2) <= timestep and count == 1:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-3) <= timestep and count == 2:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-5) <= timestep and count == 3:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-10) <= timestep and count == 4:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-20) <= timestep and count == 5:
usollist.append(usol.reshape(Np,1))
count+=1
if abs(t[i]-40) <= timestep and count == 6:
usollist.append(usol.reshape(Np,1))
count+=1
timerend = time.time()
time_elapsed = timerend-timerstart
print("Time elapsed for " + choice + " = ", time_elapsed)
return usollist,errorlist
def plot(M,start,startp1,stepdt,N_t,name,t_time):
Solution1 = FE_BE_iterator(M,start,startp1,stepdt,N_t,name,t_time)
Solution = Solution1[0]
Error = Solution1[1]
for s in range(len(Solution)):
plt.subplot(2,4,s+1)
plt.imshow((Solution[s]).reshape((Nx-2,Ny-2),order ='F'),origin='lower',extent=(ybegin,yend,xbegin,xend))
plt.colorbar()
if name == 'Newton':
plt.figure(0)
plt.plot(Error)
counter = 0
for j in ['Forward','Newton','Picard']:
plt.figure(counter+1)
if j == 'Forward':
plot(A,ut0,ut0,dt1,Nt_1,j,t_1)
elif j == 'Newton':
plot(A,ut0,ut0,dt2,Nt_2,j,t_2)
elif j == 'Picard':
plot(A,ut0,ut0,dt3,Nt_3,j,t_3)
counter+=1
gc.collect()
This produces plots such as this one:
Whereas I'd like to have them look like this:
I know the solution vector in the imshow function should be transposed, but transposing it just messes up my solution and doesn't rotate the image. How do I fix it?
EDIT: Here's what my attempt at rotating the image using the transpose gives:
I've been trying to write a solver for 15 puzzle in python but now I reached a dead end where I can't figure out what's wrong with my code. It works for simple cases, where amount of moves required to solve the puzzle is low, this one for example:
5 1 2 3
9 7 11 4
13 6 15 8
14 10 0 12
where 0 represents blank tile.
When I use more complex cases (generated here), the program seems to go into an infinite loop, and even for simple cases I feel like it's not finding the optimal solution. I've been trying to figure out what's causing the problem, but after debugging it for multiple hours I didn't find anything, all of the methods seem to work properly.
Can you tell me what is wrong with this code?
Here's the solver class:
from copy import deepcopy
class Fifteen:
heur = ''
tiles = []
undo_move = ''
h_score = 0 # calculated using heuristic
depth = 0
previous_moves = []
zero_x = 0
zero_y = 0
def __init__(self, heur, fin, parent=None):
if parent is None:
self.heur = heur
fi = open(fin, 'r', encoding='utf-8')
self.tiles = [list(map(int, line.split())) for line in fi]
self.zero_x, self.zero_y = self.find()
fi.close()
elif parent is not None:
self.heur = deepcopy(parent.heur)
self.tiles = deepcopy(parent.tiles)
self.undo_move = deepcopy(parent.undo_move)
self.depth = deepcopy(parent.depth) + 1
self.previous_moves = deepcopy(parent.previous_moves)
self.zero_x = deepcopy(parent.zero_x)
self.zero_y = deepcopy(parent.zero_y)
def find(self, tile=0):
for y in range(len(self.tiles)):
for x in range(len(self.tiles[y])):
if self.tiles[y][x] == tile:
return x, y
raise NameError
def move_tile(self, direction):
x, y = self.zero_x, self.zero_y
if direction == 'u':
self.tiles[y][x], self.tiles[y - 1][x] = self.tiles[y - 1][x], self.tiles[y][x]
self.zero_y = self.zero_y - 1
self.previous_moves.append('u')
self.undo_move = 'd'
elif direction == 'd':
self.tiles[y][x], self.tiles[y + 1][x] = self.tiles[y + 1][x], self.tiles[y][x]
self.zero_y = self.zero_y + 1
self.previous_moves.append('d')
self.undo_move = 'u'
elif direction == 'l':
self.tiles[y][x], self.tiles[y][x - 1] = self.tiles[y][x - 1], self.tiles[y][x]
self.zero_x = self.zero_x - 1
self.previous_moves.append('l')
self.undo_move = 'r'
elif direction == 'r':
self.tiles[y][x], self.tiles[y][x + 1] = self.tiles[y][x + 1], self.tiles[y][x]
self.zero_x = self.zero_x + 1
self.previous_moves.append('r')
self.undo_move = 'l'
else:
raise NameError
def generate_next_states(self):
next_states = []
x, y = self.zero_x, self.zero_y
if y != 0 and self.undo_move != 'u':
child = Fifteen(None, None, self)
child.move_tile('u')
next_states.append(child)
if y != len(self.tiles) - 1 and self.undo_move != 'd':
child = Fifteen(None, None, self)
child.move_tile('d')
next_states.append(child)
if x != 0 and self.undo_move != 'l':
child = Fifteen(None, None, self)
child.move_tile('l')
next_states.append(child)
if x != len(self.tiles[y]) - 1 and self.undo_move != 'r':
child = Fifteen(None, None, self)
child.move_tile('r')
next_states.append(child)
return next_states
def heuristic(self):
if self.heur == 'hamm':
return self.hamming()
return self.manhattan()
def hamming(self):
diff = 0
for y in range(len(self.tiles)):
for x in range(len(self.tiles[y])):
if y == len(self.tiles) - 1 and x == len(self.tiles[y]) - 1:
if self.tiles[y][x] != 0:
diff += 1
elif self.tiles[y][x] != y * len(self.tiles) + x + 1:
diff += 1
return diff
def manhattan(self):
score = 0
value = 1
for y in range(len(self.tiles)):
for x in range(len(self.tiles[y])):
if value == 16:
value = 0
x_real, y_real = self.find(value)
dx = abs(x - x_real)
dy = abs(y - y_real)
score += dx + dy
value += 1
return score
def astar(self):
queue = [self]
closed_set = {}
while len(queue) > 0:
current_state = queue.pop(0)
closed_set[repr(current_state.tiles)] = current_state
if current_state.heuristic() == 0:
print(current_state.tiles)
print(current_state.previous_moves)
print(len(current_state.previous_moves))
return
for state in current_state.generate_next_states():
if repr(state.tiles) in closed_set:
continue
state.h_score = state.heuristic()
queue.append(state)
queue.sort(key=lambda x: x.h_score, reverse=False)
print(-1)
return
And this is how I run it:
from fifteen import Fifteen
f = Fifteen('manh', "start.txt")
f.astar()
The first argument can be either manh or hamm, depending on the heuristic used, second one is name of file containing initial puzzle setup.
There are ways to improve your code, but I will explain main problems (at least for me).
1- You are not using depth values of states while sorting states. This will prevent algorithm finding optimal solutions, or even finding a solution if the state space is large.
2- You should really decide how you represent a "state". I added a equality overload (__eq__ method) for a state which I think is correct for this problem. It compares tiles, heuristic scores and depth values. Although that was not the main problem I think that is something very important. Because naive implementation may slow down your algorithm a lot and make things hard to debug.
3- When things does not work, try visualizing your algorithm. I added a PrintState function and tried to observe what is wrong with the solving process.
from copy import deepcopy
class Fifteen:
heur = ''
tiles = []
undo_move = ''
h_score = 0 # calculated using heuristic
depth = 0
previous_moves = []
zero_x = 0
zero_y = 0
def __init__(self, heur, fin, parent=None):
if parent is None:
self.heur = heur
fi = open(fin, 'r', encoding='utf-8')
self.tiles = [list(map(int, line.split())) for line in fi]
self.zero_x, self.zero_y = self.find()
fi.close()
elif parent is not None:
self.heur = deepcopy(parent.heur)
self.tiles = deepcopy(parent.tiles)
self.undo_move = deepcopy(parent.undo_move)
self.depth = deepcopy(parent.depth) + 1
self.previous_moves = deepcopy(parent.previous_moves)
self.zero_x = deepcopy(parent.zero_x)
self.zero_y = deepcopy(parent.zero_y)
def find(self, tile=0):
for y in range(len(self.tiles)):
for x in range(len(self.tiles[y])):
if self.tiles[y][x] == tile:
return x, y
raise NameError
def move_tile(self, direction):
x, y = self.zero_x, self.zero_y
if direction == 'u':
self.tiles[y][x], self.tiles[y - 1][x] = self.tiles[y - 1][x], self.tiles[y][x]
self.zero_y = self.zero_y - 1
self.previous_moves.append('u')
self.undo_move = 'd'
elif direction == 'd':
self.tiles[y][x], self.tiles[y + 1][x] = self.tiles[y + 1][x], self.tiles[y][x]
self.zero_y = self.zero_y + 1
self.previous_moves.append('d')
self.undo_move = 'u'
elif direction == 'l':
self.tiles[y][x], self.tiles[y][x - 1] = self.tiles[y][x - 1], self.tiles[y][x]
self.zero_x = self.zero_x - 1
self.previous_moves.append('l')
self.undo_move = 'r'
elif direction == 'r':
self.tiles[y][x], self.tiles[y][x + 1] = self.tiles[y][x + 1], self.tiles[y][x]
self.zero_x = self.zero_x + 1
self.previous_moves.append('r')
self.undo_move = 'l'
else:
raise NameError
def generate_next_states(self):
next_states = []
x, y = self.zero_x, self.zero_y
if y != 0 and self.undo_move != 'u':
child = Fifteen(None, None, self)
child.move_tile('u')
next_states.append(child)
if y != len(self.tiles) - 1 and self.undo_move != 'd':
child = Fifteen(None, None, self)
child.move_tile('d')
next_states.append(child)
if x != 0 and self.undo_move != 'l':
child = Fifteen(None, None, self)
child.move_tile('l')
next_states.append(child)
if x != len(self.tiles[y]) - 1 and self.undo_move != 'r':
child = Fifteen(None, None, self)
child.move_tile('r')
next_states.append(child)
return next_states
def heuristic(self):
if self.heur == 'hamm':
return self.hamming()
return self.manhattan()
def hamming(self):
diff = 0
for y in range(len(self.tiles)):
for x in range(len(self.tiles[y])):
if y == len(self.tiles) - 1 and x == len(self.tiles[y]) - 1:
if self.tiles[y][x] != 0:
diff += 1
elif self.tiles[y][x] != y * len(self.tiles) + x + 1:
diff += 1
return diff
def manhattan(self):
score = 0
value = 1
for y in range(len(self.tiles)):
for x in range(len(self.tiles[y])):
if value == 16:
value = 0
x_real, y_real = self.find(value)
dx = abs(x - x_real)
dy = abs(y - y_real)
#print("dx + dy for {}: {}".format(value, dx+dy))
score += dx + dy
value += 1
#print("Score:{}".format(score))
return score
def PrintState(self):
for y in range(len(self.tiles)):
for x in range(len(self.tiles[y])):
cellValue = self.tiles[y][x]
print(cellValue, end=" ")
print("")
def __eq__(self, other):
return (self.tiles == other.tiles
and self.h_score == other.h_score
and self.depth == other.depth)
def astar(self):
queue = [self]
closed_set = {}
while len(queue) > 0:
print("---")
print("---")
current_state = queue.pop(0)
print("current state")
#print(current_state.tiles)
#print(repr(current_state.tiles))
current_state.PrintState()
print("current scores")
print("heuristic:{}".format(current_state.heuristic()))
print("depth:{}".format(current_state.depth))
print("total:{}".format(current_state.heuristic() + current_state.depth))
closed_set[repr(current_state.tiles)] = current_state
if current_state.heuristic() == 0:
print(current_state.tiles)
print(current_state.previous_moves)
print(len(current_state.previous_moves))
return
for state in current_state.generate_next_states():
if repr(state.tiles) in closed_set:
continue
state.h_score = state.heuristic()
queue.append(state)
queue.sort(key=lambda x: (x.h_score + x.depth), reverse=False)
print(-1)
return
Optionally, consider using priority queue based implementation.
Update: Beware unsolvable starting positions like:
1 2 3 4
5 6 10 8
9 7 11 12
15 13 14 0
I wasted a good time on this configuration :)
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.
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[]