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

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)

Related

Is this function i wrote to find prime numbers efficient [duplicate]

This question already has answers here:
Big O, how do you calculate/approximate it?
(24 answers)
Closed 2 years ago.
def is_prime(x):
'''
Function to check if a number is prime
'''
if x == 2:
return True
if x%2 != 0: #Check if number is even since all primes are odd except 2
a = [x % i for i in range(2,x+1)]
b = [i for i in a if i == 0] # Checks to make sure there's only one modulus of 0
if len(b) == 1:
return True
else:
return False
else:
return False
So like yeah please what is the time complexity (all those 0/n things) and how do i find that, a good resource link would be helpful (:
Your complexity is O(x) as you run one loop from 2 to x+1.
You can just check upto sqrt(x). That will bring down the complexity to O(sqrt(x)). (You can break once you find one factor, even though it won't bring down the worst time complexity)
Just change this line -
a = [x % i for i in range(2,math.sqrt(x+1))]
Why up to square root?
You can just google, there are many proofs. The simple one being, if
a = b.c, then the at least there is one divisor of a which is less than sqrt(a), or equal if a is square number a = b*b.
There are many fast heuristic and probabilistic (Miller-Rabin is very famous and frequently used) algorithms for faster prime detection.
Here's one which is deterministic:
The Adleman–Pomerance–Rumely primality test is an algorithm for determining whether a number is prime. Unlike other, more efficient algorithms for this purpose, it avoids the use of random numbers, so it is a deterministic primality test.
It's complexity is log(x)^O(logloglogx)
import copy
import time
from math import gcd # version >= 3.5
# primality test by trial division
def isprime_slow(n):
if n<2:
return False
elif n==2 or n==3:
return True
elif n%2==0:
return False
else:
i = 3
while i*i <= n:
if n%i == 0:
return False
i+=2
return True
# v_q(t): how many time is t divided by q
def v(q, t):
ans = 0
while(t % q == 0):
ans +=1
t//= q
return ans
def prime_factorize(n):
ret = []
p=2
while p*p <= n:
if n%p==0:
num = 0
while n%p==0:
num+=1
n//= p
ret.append((p,num))
p+= 1
if n!=1:
ret.append((n,1))
return ret
# calculate e(t)
def e(t):
s = 1
q_list = []
for q in range(2, t+2):
if t % (q-1) == 0 and isprime_slow(q):
s *= q ** (1+v(q,t))
q_list.append(q)
return 2*s, q_list
# Jacobi sum
class JacobiSum(object):
def __init__(self, p, k, q):
self.p = p
self.k = k
self.q = q
self.m = (p-1)*p**(k-1)
self.pk = p**k
self.coef = [0]*self.m
# 1
def one(self):
self.coef[0] = 1
for i in range(1,self.m):
self.coef[i] = 0
return self
# product of JacobiSum
# jac : JacobiSum
def mul(self, jac):
m = self.m
pk = self.pk
j_ret=JacobiSum(self.p, self.k, self.q)
for i in range(m):
for j in range(m):
if (i+j)% pk < m:
j_ret.coef[(i+j)% pk] += self.coef[i] * jac.coef[j]
else:
r = (i+j) % pk - self.p ** (self.k-1)
while r>=0:
j_ret.coef[r] -= self.coef[i] * jac.coef[j]
r-= self.p ** (self.k-1)
return j_ret
def __mul__(self, right):
if type(right) is int:
# product with integer
j_ret=JacobiSum(self.p, self.k, self.q)
for i in range(self.m):
j_ret.coef[i] = self.coef[i] * right
return j_ret
else:
# product with JacobiSum
return self.mul(right)
# power of JacobiSum(x-th power mod n)
def modpow(self, x, n):
j_ret=JacobiSum(self.p, self.k, self.q)
j_ret.coef[0]=1
j_a = copy.deepcopy(self)
while x>0:
if x%2==1:
j_ret = (j_ret * j_a).mod(n)
j_a = j_a*j_a
j_a.mod(n)
x //= 2
return j_ret
# applying "mod n" to coefficient of self
def mod(self, n):
for i in range(self.m):
self.coef[i] %= n
return self
# operate sigma_x
# verification for sigma_inv
def sigma(self, x):
m = self.m
pk = self.pk
j_ret=JacobiSum(self.p, self.k, self.q)
for i in range(m):
if (i*x) % pk < m:
j_ret.coef[(i*x) % pk] += self.coef[i]
else:
r = (i*x) % pk - self.p ** (self.k-1)
while r>=0:
j_ret.coef[r] -= self.coef[i]
r-= self.p ** (self.k-1)
return j_ret
# operate sigma_x^(-1)
def sigma_inv(self, x):
m = self.m
pk = self.pk
j_ret=JacobiSum(self.p, self.k, self.q)
for i in range(pk):
if i<m:
if (i*x)%pk < m:
j_ret.coef[i] += self.coef[(i*x)%pk]
else:
r = i - self.p ** (self.k-1)
while r>=0:
if (i*x)%pk < m:
j_ret.coef[r] -= self.coef[(i*x)%pk]
r-= self.p ** (self.k-1)
return j_ret
# Is self p^k-th root of unity (mod N)
# if so, return h where self is zeta^h
def is_root_of_unity(self, N):
m = self.m
p = self.p
k = self.k
# case of zeta^h (h<m)
one = 0
for i in range(m):
if self.coef[i]==1:
one += 1
h = i
elif self.coef[i] == 0:
continue
elif (self.coef[i] - (-1)) %N != 0:
return False, None
if one == 1:
return True, h
# case of zeta^h (h>=m)
for i in range(m):
if self.coef[i]!=0:
break
r = i % (p**(k-1))
for i in range(m):
if i % (p**(k-1)) == r:
if (self.coef[i] - (-1))%N != 0:
return False, None
else:
if self.coef[i] !=0:
return False, None
return True, (p-1)*p**(k-1)+ r
# find primitive root
def smallest_primitive_root(q):
for r in range(2, q):
s = set({})
m = 1
for i in range(1, q):
m = (m*r) % q
s.add(m)
if len(s) == q-1:
return r
return None # error
# calculate f_q(x)
def calc_f(q):
g = smallest_primitive_root(q)
m = {}
for x in range(1,q-1):
m[pow(g,x,q)] = x
f = {}
for x in range(1,q-1):
f[x] = m[ (1-pow(g,x,q))%q ]
return f
# sum zeta^(a*x+b*f(x))
def calc_J_ab(p, k, q, a, b):
j_ret = JacobiSum(p,k,q)
f = calc_f(q)
for x in range(1,q-1):
pk = p**k
if (a*x+b*f[x]) % pk < j_ret.m:
j_ret.coef[(a*x+b*f[x]) % pk] += 1
else:
r = (a*x+b*f[x]) % pk - p**(k-1)
while r>=0:
j_ret.coef[r] -= 1
r-= p**(k-1)
return j_ret
# calculate J(p,q)(p>=3 or p,q=2,2)
def calc_J(p, k, q):
return calc_J_ab(p, k, q, 1, 1)
# calculate J_3(q)(p=2 and k>=3)
def calc_J3(p, k, q):
j2q = calc_J(p, k, q)
j21 = calc_J_ab(p, k, q, 2, 1)
j_ret = j2q * j21
return j_ret
# calculate J_2(q)(p=2 and k>=3)
def calc_J2(p, k, q):
j31 = calc_J_ab(2, 3, q, 3, 1)
j_conv = JacobiSum(p, k, q)
for i in range(j31.m):
j_conv.coef[i*(p**k)//8] = j31.coef[i]
j_ret = j_conv * j_conv
return j_ret
# in case of p>=3
def APRtest_step4a(p, k, q, N):
print("Step 4a. (p^k, q = {0}^{1}, {2})".format(p,k,q))
J = calc_J(p, k, q)
# initialize s1=1
s1 = JacobiSum(p,k,q).one()
# J^Theta
for x in range(p**k):
if x % p == 0:
continue
t = J.sigma_inv(x)
t = t.modpow(x, N)
s1 = s1 * t
s1.mod(N)
# r = N mod p^k
r = N % (p**k)
# s2 = s1 ^ (N/p^k)
s2 = s1.modpow(N//(p**k), N)
# J^alpha
J_alpha = JacobiSum(p,k,q).one()
for x in range(p**k):
if x % p == 0:
continue
t = J.sigma_inv(x)
t = t.modpow((r*x)//(p**k), N)
J_alpha = J_alpha * t
J_alpha.mod(N)
# S = s2 * J_alpha
S = (s2 * J_alpha).mod(N)
# Is S root of unity
exist, h = S.is_root_of_unity(N)
if not exist:
# composite!
return False, None
else:
# possible prime
if h%p!=0:
l_p = 1
else:
l_p = 0
return True, l_p
# in case of p=2 and k>=3
def APRtest_step4b(p, k, q, N):
print("Step 4b. (p^k, q = {0}^{1}, {2})".format(p,k,q))
J = calc_J3(p, k, q)
# initialize s1=1
s1 = JacobiSum(p,k,q).one()
# J3^Theta
for x in range(p**k):
if x % 8 not in [1,3]:
continue
t = J.sigma_inv(x)
t = t.modpow(x, N)
s1 = s1 * t
s1.mod(N)
# r = N mod p^k
r = N % (p**k)
# s2 = s1 ^ (N/p^k)
s2 = s1.modpow(N//(p**k), N)
# J3^alpha
J_alpha = JacobiSum(p,k,q).one()
for x in range(p**k):
if x % 8 not in [1,3]:
continue
t = J.sigma_inv(x)
t = t.modpow((r*x)//(p**k), N)
J_alpha = J_alpha * t
J_alpha.mod(N)
# S = s2 * J_alpha * J2^delta
if N%8 in [1,3]:
S = (s2 * J_alpha ).mod(N)
else:
J2_delta = calc_J2(p,k,q)
S = (s2 * J_alpha * J2_delta).mod(N)
# Is S root of unity
exist, h = S.is_root_of_unity(N)
if not exist:
# composite
return False, None
else:
# possible prime
if h%p!=0 and (pow(q,(N-1)//2,N) + 1)%N==0:
l_p = 1
else:
l_p = 0
return True, l_p
# in case of p=2 and k=2
def APRtest_step4c(p, k, q, N):
print("Step 4c. (p^k, q = {0}^{1}, {2})".format(p,k,q))
J2q = calc_J(p, k, q)
# s1 = J(2,q)^2 * q (mod N)
s1 = (J2q * J2q * q).mod(N)
# s2 = s1 ^ (N/4)
s2 = s1.modpow(N//4, N)
if N%4 == 1:
S = s2
elif N%4 == 3:
S = (s2 * J2q * J2q).mod(N)
else:
print("Error")
# Is S root of unity
exist, h = S.is_root_of_unity(N)
if not exist:
# composite
return False, None
else:
# possible prime
if h%p!=0 and (pow(q,(N-1)//2,N) + 1)%N==0:
l_p = 1
else:
l_p = 0
return True, l_p
# in case of p=2 and k=1
def APRtest_step4d(p, k, q, N):
print("Step 4d. (p^k, q = {0}^{1}, {2})".format(p,k,q))
S2q = pow(-q, (N-1)//2, N)
if (S2q-1)%N != 0 and (S2q+1)%N != 0:
# composite
return False, None
else:
# possible prime
if (S2q + 1)%N == 0 and (N-1)%4==0:
l_p=1
else:
l_p=0
return True, l_p
# Step 4
def APRtest_step4(p, k, q, N):
if p>=3:
result, l_p = APRtest_step4a(p, k, q, N)
elif p==2 and k>=3:
result, l_p = APRtest_step4b(p, k, q, N)
elif p==2 and k==2:
result, l_p = APRtest_step4c(p, k, q, N)
elif p==2 and k==1:
result, l_p = APRtest_step4d(p, k, q, N)
else:
print("error")
if not result:
print("Composite")
return result, l_p
def APRtest(N):
t_list = [
2,
12,
60,
180,
840,
1260,
1680,
2520,
5040,
15120,
55440,
110880,
720720,
1441440,
4324320,
24504480,
73513440
]
print("N=", N)
if N<=3:
print("input should be greater than 3")
return False
# Select t
for t in t_list:
et, q_list = e(t)
if N < et*et:
break
else:
print("t not found")
return False
print("t=", t)
print("e(t)=", et, q_list)
# Step 1
print("=== Step 1 ===")
g = gcd(t*et, N)
if g > 1:
print("Composite")
return False
# Step 2
print("=== Step 2 ===")
l = {}
fac_t = prime_factorize(t)
for p, k in fac_t:
if p>=3 and pow(N, p-1, p*p)!=1:
l[p] = 1
else:
l[p] = 0
print("l_p=", l)
# Step 3 & Step 4
print("=== Step 3&4 ===")
for q in q_list:
if q == 2:
continue
fac = prime_factorize(q-1)
for p,k in fac:
# Step 4
result, l_p = APRtest_step4(p, k, q, N)
if not result:
# composite
print("Composite")
return False
elif l_p==1:
l[p] = 1
# Step 5
print("=== Step 5 ===")
print("l_p=", l)
for p, value in l.items():
if value==0:
# try other pair of (p,q)
print("Try other (p,q). p={}".format(p))
count = 0
i = 1
found = False
# try maximum 30 times
while count < 30:
q = p*i+1
if N%q != 0 and isprime_slow(q) and (q not in q_list):
count += 1
k = v(p, q-1)
# Step 4
result, l_p = APRtest_step4(p, k, q, N)
if not result:
# composite
print("Composite")
return False
elif l_p == 1:
found = True
break
i += 1
if not found:
print("error in Step 5")
return False
# Step 6
print("=== Step 6 ===")
r = 1
for t in range(t-1):
r = (r*N) % et
if r!=1 and r!= N and N % r == 0:
print("Composite", r)
return False
# prime!!
print("Prime!")
return True
if __name__ == '__main__':
start_time = time.time()
APRtest(2**521-1) # 157 digit, 18 sec
# APRtest(2**1279-1) # 386 digit, 355 sec
# APRtest(2074722246773485207821695222107608587480996474721117292752992589912196684750549658310084416732550077)
end_time = time.time()
print(end_time - start_time, "sec")
credit: https://github.com/wacchoz/APR_CL/blob/master/APR_CL.py
You only need to test odd numbers, except for 2 which you can test specially before the loop. This doesn't change the complexity, since it's a constant factor, but it reduces the time in half.
You should only test numbers up to math.sqrt(x). This changes the worst case complexity from O(n) to O(sqrt(n)).
You should stop as soon as you find a factor, rather than creating a list of all the x % i. This improves the best case complexity.
import math
def is_prime(x):
'''
Function to check if a number is prime
'''
if x == 2:
return True
if x % 2 == 0:
return False
for i in range(3, int(math.sqrt(x))+1, 2):
if x % i == 0:
return False
return True
Even better than checking all odd numbers is to check only prime numbers, using the Sieve of Eratosthenes.

Iterative Deepening Search for K-puzzle

I am trying to implement iterative deepening search for the k - puzzle. I have managed to find the goal node. However, I am unable to backtrack from the goal node to the start node to find the optimal moves. I think it has something to do with repeated states in IDS. Currently, I am keeping track of all visited states in the IDS algorithm.
This is the current implementation of my algorithm. In the code below, moves_dict stores each node's previous state and move to get to current state.
import os
import sys
from itertools import chain
from collections import deque
# Iterative Deepening Search (IDS)
class Node:
def __init__(self, state, empty_pos = None, depth = 0):
self.state = state
self.depth = depth
self.actions = ["UP", "DOWN", "LEFT", "RIGHT"]
if empty_pos is None:
self.empty_pos = self.find_empty_pos(self.state)
else:
self.empty_pos = empty_pos
def find_empty_pos(self, state):
for x in range(n):
for y in range(n):
if state[x][y] == 0:
return (x, y)
def find_empty_pos(self, state):
for x in range(n):
for y in range(n):
if state[x][y] == 0:
return (x, y)
def do_move(self, move):
if move == "UP":
return self.up()
if move == "DOWN":
return self.down()
if move == "LEFT":
return self.left()
if move == "RIGHT":
return self.right()
def swap(self, state, (x1, y1), (x2, y2)):
temp = state[x1][y1]
state[x1][y1] = state[x2][y2]
state[x2][y2] = temp
def down(self):
empty = self.empty_pos
if (empty[0] != 0):
t = [row[:] for row in self.state]
pos = (empty[0] - 1, empty[1])
self.swap(t, pos, empty)
return t, pos
else:
return self.state, empty
def up(self):
empty = self.empty_pos
if (empty[0] != n - 1):
t = [row[:] for row in self.state]
pos = (empty[0] + 1 , empty[1])
self.swap(t, pos, empty)
return t, pos
else:
return self.state, empty
def right(self):
empty = self.empty_pos
if (empty[1] != 0):
t = [row[:] for row in self.state]
pos = (empty[0] , empty[1] - 1)
self.swap(t, pos, empty)
return t, pos
else:
return self.state, empty
def left(self):
empty = self.empty_pos
if (empty[1] != n - 1):
t = [row[:] for row in self.state]
pos = (empty[0] , empty[1] + 1)
self.swap(t, pos, empty)
return t, pos
else:
return self.state, empty
class Puzzle(object):
def __init__(self, init_state, goal_state):
self.init_state = init_state
self.state = init_state
self.goal_state = goal_state
self.total_nodes = 1
self.total_visited = 0
self.max_frontier = 0
self.depth = 0
self.visited = {}
self.frontier_node = []
self.move_dict = {}
def is_goal_state(self, node):
return node.state == self.goal_state
def is_solvable(self):
flat_list = list(chain.from_iterable(self.init_state))
num_inversions = 0
for i in range(max_num):
current = flat_list[i]
for j in range(i + 1, max_num + 1):
next = flat_list[j]
if current > next and next != 0:
num_inversions += 1
if n % 2 != 0 and num_inversions % 2 == 0:
return True
elif n % 2 == 0:
row_with_blank = n - flat_list.index(0) // n
return (row_with_blank % 2 == 0) == (num_inversions % 2 != 0)
else:
return False
def succ(self, node, frontier):
succs = deque()
node_str = str(node.state)
self.visited[node_str] = node.depth
self.total_visited += 1
frontier -= 1
for m in node.actions:
transition, t_empty = node.do_move(m)
transition_str = str(transition)
transition_depth = node.depth + 1
if transition_str not in self.visited or transition_depth < self.visited[transition_str]:
self.total_nodes += 1
transition_depth = node.depth + 1
transition_str = str(transition)
self.move_dict[transition_str] = (node_str, m)
succs.append(Node(transition, t_empty, transition_depth))
frontier += 1
return succs , frontier
def depth_limited(self, node, depth, frontier):
if self.is_goal_state(node):
return node
if node.depth >= depth:
return None
succs, frontier = self.succ(node, frontier)
self.max_frontier = max(self.max_frontier, frontier)
while succs:
result = self.depth_limited(succs.popleft(), depth, frontier)
if result is not None:
return result
return None
def solve(self):
if not self.is_solvable():
return ["UNSOLVABLE"]
goal_node = None
while goal_node is None:
goal_node = self.depth_limited(Node(self.init_state), self.depth, 1)
if goal_node is not None:
break
# reset statistics
self.visited = {}
self.total_nodes = 1
self.move_dict = {}
self.depth += 1
print self.depth
print "out"
print goal_node.state
solution = deque()
init_str = str(self.init_state)
current_str = str(goal_node.state)
while current_str != init_str:
current_str, move = self.move_dict[current_str]
solution.appendleft(move)
print "Total number of nodes generated: " + str(self.total_nodes)
print "Total number of nodes explored: " + str(self.total_visited)
print "Maximum number of nodes in frontier: " + str(self.max_frontier)
print "Solution depth: " + str(self.depth)
return solution
I have been cracking my head for awhile now. I use a hashMap that maps the state string to its depth and when adds the node whenever the same state appears in a shallower depth
EDIT
Optimal solution depth for this test case is 22.
init state: [[1,8,3],[5,2,4],[0,7,6]]
Goal state: [[1,2,3],[4,5,6],[7,8,0]]
im not going to implement your k puzzle but consider the following datastruct
d = {'A':{'B':{'Z':7,'Q':9},'R':{'T':0}},'D':{'G':1}}
def find_node(search_space,target,path_so_far=None):
if not path_so_far: # empty path to start
path_so_far = []
for key,value in search_space.items():
if value == target:
# found the value return the path
return path_so_far+[key]
else:
# pass the path so far down to the next step of the search space
result = find_node(search_space[key],target, path_so_far+[key])
if result:
print("Found Path:",result)
return result

How to create an algorithm from pseudo code to uniform cost search?

As we know from daily experience diagonal moves are cheaper than a
horizontal + vertical moves, this becomes a problem of uneven step cost.
So, uniform cost search will be required to solve this problem.
To implement uniform cost search, you will need a Priority Queue for frontier.
To add a child to the frontier
frontier.insert(item)
To extract the item with minimum cost
Temp = frontier.extract_min()
To decrease the cost of an item
frontier.decrease_key(item)
To check if in an item is already in the frontier
frontier.is_in(item)
It returns true if item is in the frontier, returns false if not in the frontier.
Algorithm I used for this code :
import collections
import copy
grid_size = 5
source = (0, 0)
destination = (4, 3)
grid = [[0, 0, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]]
class Location:
def __init__(self, p, cost=0):
self.point = p
self.parent = None
self.cost = cost
self.hash_value = self.hash_calc()
def hash_calc(self):
x, y = self.point
return str(x) + "_" + str(y)
def make_move(self, direction):
x, y = self.point
# up
if direction == 'l':
if y > 0 and grid[x][y-1] == 0:
self.point = x, y-1
self.cost = self.cost + 1
# down
elif direction == 'r':
if y < grid_size-1 and grid[x][y+1] == 0:
self.point = x, y+1
self.cost = self.cost + 1
# left
elif direction == 'u':
if x > 0 and grid[x-1][y] == 0:
self.point = x-1, y
self.cost = self.cost + 1
# right
elif direction == 'd':
if x < grid_size-1 and grid[x+1][y] == 0:
self.point = x+1, y
self.cost = self.cost + 1
# up-left
elif direction == 'ul':
if y>0 and x>0 and grid[x-1][y-1] == 0:
self.point = x-1, y-1
self.cost = self.cost + 1.5
# up-right
elif direction == 'dl':
if y>0 and x<grid_size-1 and grid[x+1][y-1] == 0:
self.point = x+1, y-1
self.cost = self.cost + 1.5
# down-left
elif direction == 'ur':
if y<grid_size-1 and x>0 and grid[x-1][y+1] == 0:
self.point = x-1, y+1
self.cost = self.cost + 1.5
# down-right
elif direction == 'dr':
if y<grid_size-1 and x<grid_size-1 and grid[x+1][y+1] == 0:
self.point = x+1, y+1
self.cost = self.cost + 1.5
self.hash_value = self.hash_calc()
print(self.point, self.cost)
def copy_location(self):
temp = Location(self.point, cost=self.cost)
temp.parent = self
return temp
def print_path(self):
ancestors = []
temp = self
while(temp.parent != None):
ancestors.append(temp.parent)
temp = temp.parent
n = len(ancestors)
for i in range(n):
temp = ancestors.pop()
print(temp.point, end='->')
print(self.point)
print('%d steps were required.\nTotal cost is %f' % (n, self.cost))
def goal_test(self):
return self.point == destination
def get_key(self):
return self.cost
class Priority_Queue:
def __init__(self):
self.capacity = 2
self.q = [None] * self.capacity
self.items = [None] * self.capacity
self.dict = {}
self.size = 0
def parent(self, i):
return int((i-1)/2)
def left(self, i):
return 2*i + 1
def right(self, i):
return 2*i + 2
def move(self, i, j):
self.q[i] = self.q[j]
self.items[i] = self.items[j]
self.dict[self.items[i].hash_value] = i
def swap(self, i, j):
self.q[i], self.q[j] = self.q[j], self.q[i]
self.items[i], self.items[j] = self.items[j], self.items[i]
self.dict[self.items[i].hash_value] = i
self.dict[self.items[j].hash_value] = j
def min_heapify(self, i):
left = self.left(i)
right = self.right(i)
smallest = i
if left < self.size and self.q[left] < self.q[i]:
smallest = left
if right < self.size and self.q[right] < self.q[smallest]:
smallest = right
if smallest != i:
self.swap(i, smallest)
self.min_heapify(smallest)
def insert(self, item):
self.size = self.size + 1
if self.size > self.capacity:
self.q = self.q + [None] * self.capacity
self.items = self.items + [None] * self.capacity
self.capacity = self.capacity * 2
i = self.size - 1
self.q[i] = item.get_key()
self.items[i] = item
self.dict[item.hash_value] = i
while i != 0 and self.q[self.parent(i)] > self.q[i]:
self.swap(i, self.parent(i))
i = self.parent(i)
def extract_min(self):
item = self.items[0]
self.move(0, self.size - 1)
self.dict.pop(item.hash_value)
self.size = self.size - 1
self.min_heapify(0)
return item
def decrease_key(self, item):
i = self.dict[item.hash_value]
if self.q[i] < item.get_key():
return
self.q[i] = item.get_key()
self.items[i] = item
while i != 0 and self.q[self.parent(i)] > self.q[i]:
self.swap(i, self.parent(i))
i = self.parent(i)
def get_min(self):
return self.items[0]
def is_in(self, item):
return item.hash_value in self.dict.keys()
# Make an initial State with source
initial_state = Location(source)
# Create an empty frontier
frontier = Priority_Queue()
frontier.insert(initial_state)
# Create an empty explored list
explored = set()
# initialize frontier with initial state
##########################################
####Solution would be here
##############Solution i Tried to solve
x = 0
children=()
Output = False
#While Output is False
while Output == False:
x = x+1
if frontier.size == 0:
print('No Solution Found !')
break
z = frontier.get_min()
explored.add(z)
#make moves
for d in ['u','d','l','r','ul','dl','ur','dr']:
children = z.copy_location()
children.make_move(d)
if children not in explored and children:
if children.goal_test() == True:
children.print_path()
Output = True
break
frontier.insert(children)
#if output is true
if Output == True:
print('Total %d states Explored !.' %(x))
break
i want to implement uniform cost search here. i tried to follow the pseudo code but i failed.
well this is my first time in stack overflow so if i made any mistake please forgive me !
i will be more careful from next time.

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.

how to solve the print string error on python eclipse

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[]

Categories

Resources