binary heap/Give the class a max value - python

Below is what I have done but it Does not handle the max requirement on insert.
how do I Give the class a max value and check it in the insert and then remove the least significant element. Then figure out what is the least significant element in the implementation.
Having some issues trying to figure this out.
import math
import random
class BinaryHeap:
def __init__(self, array, direction=1, size=100):
if(size > len(array)):
self.size = len(array)
else:
self.size = size;
self.bBinaryHeap = array[:]
if 0 < direction:
self.compare = self.greater
else:
self.compare = self.less
self.buildBinaryHeap()
def node(self, index):
return (index << 1) + 1
def parent(self, index):
return (index - 1) >> 1
def bBinaryHeapifyDown(self, index):
swap = self.bBinaryHeap[index]
while self.node(index) < self.size:
node = self.node(index)
if node + 1 < self.size and self.compare(self.bBinaryHeap[node], self.bBinaryHeap[node + 1]) > 0:
node += 1
if self.compare(swap, self.bBinaryHeap[node]) > 0:
self.bBinaryHeap[index] = self.bBinaryHeap[node];
else:
break
index = node
self.bBinaryHeap[index] = swap
def upheapify(self, index):
while 0 < index and self.compare(self.bBinaryHeap[index], self.bBinaryHeap[self.parent(index)]) < 0:
parent = self.parent(index)
swap = self.bBinaryHeap[parent]
self.bBinaryHeap[parent] = self.bBinaryHeap[index]
self.bBinaryHeap[index] = swap
index = parent
def buildBinaryHeap(self):
indices = range(0, int(self.size / 2))
reversed(indices)
for index in indices:
self.bBinaryHeapifyDown(index)
def insert(self, value):
self.shrink()
index = self.size
self.bBinaryHeap[index] = value
self.size += 1
self.upheapify(index)
def search(self, value):
for index in range(self.size):
if self.bBinaryHeap[index] == value:
return index
def delete(self, value):
index = self.search(value)
self.size -= 1
self.bBinaryHeap[index] = self.bBinaryHeap[self.size]
parent = self.parent(index)
if (index == 0) or (self.compare(self.bBinaryHeap[parent], self.bBinaryHeap[index]) < 0):
self.bBinaryHeapifyDown(index)
else:
self.upheapify(index)
def shrink(self):
capacity = len(self.bBinaryHeap)
if capacity == self.size:
self.bBinaryHeap.extend([0] * capacity)
def greater(self, value1, value2):
if value1 == value2:
return 0
elif value1 < value2:
return 1
elif value1 > value2:
return -1
def less(self, value1, value2):
if value1 == value2:
return 0
elif value1 < value2:
return -1
elif value1 > value2:
return 1
def getLevel(self, index):
return int(math.floor(math.log(index + 1, 2)))
def displayBinaryHeap(self):
printBinaryHeap = str(self.bBinaryHeap)
height = self.getLevel(self.size)
previous = -1
for index in range(self.size):
getLevel = self.getLevel(index)
n = height - getLevel
indent = int(math.pow(2, n + 1) - 2)
spacing = 2 * indent
if getLevel != previous:
printBinaryHeap += '\n'
printBinaryHeap += ' ' * indent
previous = getLevel
else:
printBinaryHeap += ' ' * spacing
printBinaryHeap += '%4d' % self.bBinaryHeap[index]
print(printBinaryHeap)
if __name__ == "__main__":
size =10
array = [random.randint(0, 100) for i in range(size)]
bBinaryHeap = BinaryHeap(array, 1, 100)
print('Binary bBinaryHeap:')
bBinaryHeap.displayBinaryHeap()

Your code has numerous indentation errors. In python, indentation counts.
As for this code:
if 0 < direction:
self.compare = self.greater
else:
self.compare = self.less
self.greater and self.less don't exist. You are doing the equivalent of this:
x = elephant
That's nice, but unless you've set the variable elephant to some value prior to that line, that is an error.
how do I Give the class a max value
class BinaryHeap:
pass
BinaryHeap.max = 10
print(BinaryHeap.max)
--output:--
10
and check it in the insert
class BinaryHeap:
max = 10
def insert(self):
print(self.max)
bh = BinaryHeap()
bh.insert()
--output:--
10
then remove the least significant element
x = 0b1111
print(x) #15
y = x >> 1
print("{:b}".format(y)) #111
print(y) #7
Then figure out what is the least significant element in the implementation
x = 0b1110
print(x) #=>14
b_str = "{:b}".format(x)
print(repr(b_str)) #=> '1110'
for direction in [1, -1]:
if direction > 0:
least_signif = b_str[-1]
else:
least_signif = b_str[0]
print(least_signif)
--output:--
0
1

Related

Getting Wrong ancestor for the right side of the tree

So I was trying to implement LCA using Euler tour and RMQ with Sparse Table in python. My code is working fine, if I insert number from left side of the tree. The code for building the tree is:
The node class has data, left_child and right_child:
class Node:
def __init__(self, value):
self.data = value
self.right_child = None
self.left_child = None
Then I have a tree class which I used to build the tree:
class Tree:
content = []
def __init__(self):
self.root = None
def add_child(self, arr, root, i, n):
if i < n:
temp = Node(arr[i])
root = temp
root.left_child = self.add_child(arr, root.left_child, 2 * i + 1, n)
root.right_child = self.add_child(arr, root.right_child, 2 * i + 2, n)
return root
def pre_order(self, root):
if root != None:
Tree.content.append(root.data)
self.pre_order(root.left_child)
self.pre_order(root.right_child)
return Tree.content
Finally, I got an LCA class which mainly contains the function for building the sparse table, then do a RMQ on the sparse table, then a function that does the part of the euler tour and finally the function for finding LCA.
class LCA:
def __init__(self, root, length):
self.pre_process_array = [[0] * (math.floor(math.log2(length) + 2)) for _ in range((length * 2) - 1)]
self.euler = [0] * (length * 2 - 1)
self.height = [0] * (length * 2 - 1)
self.index = [-1 for _ in range(length + 1)]
self.tour = 0
self.euler_tour(root, 0)
self.build_sparse_table(self.height)
print(self.pre_process_array)
def build_sparse_table(self, height_array):
for i in range(len(height_array)):
self.pre_process_array[i][0] = height_array[i]
j = 1
while (1 << j) <= len(height_array):
i = 0
while (i + (1 << j) - 1) < len(height_array):
if self.pre_process_array[i][j - 1] < self.pre_process_array[i + (1 << (j - 1))][j-1]:
self.pre_process_array[i][j] = self.pre_process_array[i][j - 1]
else:
self.pre_process_array[i][j] = self.pre_process_array[i + (1 << (j - 1))][j - 1]
i += 1
j += 1
def rmq(self, l, h):
j = int(math.log2(h - l + 1))
if self.pre_process_array[l][j] <= self.pre_process_array[h - (1 << j) + 1][j]:
return self.pre_process_array[l][j]
else:
return self.pre_process_array[h - (1 << j) + 1][j]
def euler_tour(self, root, level):
if root is not None:
self.euler[self.tour] = root.data
self.height[self.tour] = level
self.tour += 1
if self.index[root.data] == -1:
self.index[root.data] = self.tour - 1
if root.left_child is not None:
self.euler_tour(root.left_child, level + 1)
self.euler[self.tour] = root.data
self.height[self.tour] = level
self.tour += 1
if root.right_child is not None:
self.euler_tour(root.right_child, level + 1)
self.euler[self.tour] = root.data
self.height[self.tour] = level
self.tour += 1
def find_LCA(self, val1, val2):
if val1 >= len(self.index) or val2 >= len(self.index) or self.index[val1] == -1 or self.index[val2] == -1:
return -1
if self.index[val1] > self.index[val2]:
return self.euler[self.rmq(self.index[val2], self.index[val1])]
elif self.index[val2] > self.index[val1]:
return self.euler[self.rmq(self.index[val1], self.index[val2])]
And my driver code is as follow:
tree_data = [1,2,3,4,5,6,7,8,9]
length = len(tree_data)
tree = Tree()
root = tree.root
tree.root = tree.add_child(tree_data, root, 0, length)
l = LCA(tree.root, length)
print(l.find_LCA(6, 3))
so, my tree should something look like:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
Now, if I try to find the LCA(8, 9) or LCA(4, 3), I get the correct output but whenever I try to give LCA(6, 7) or LCA(3, 7), It always keeps returning 2 as the answer where it should return 3 and 3 respectively.
I don't have any idea where is the mistake as, from my side it looks pretty fine.

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.

Counting probes for quadratic probing

I'm trying to count the number of probes (or number of indices that must be passed over) when inserting keys into a list using quadratic probing
I have
def hash_quadratic(key, values):
tablesize=len(values)
index=key%tablesize
probes=0
if values[index] is None:
values[index]=key
probes+=1
return probes
else:
while values[index] is not None:
index = (index+1**2)% tablesize
probes+=1
values[index]=key
return probes
I think this just counts every time the index changes but doesn't count the number of indices that it crosses over. How do I count every index that the key passes?
If you would like to implement Quadratic probe on a hash table, you need more than the function you have written. The following class does the job you are looking for:
class HashTable(object):
def __init__(self, size=200):
self.size = size
self.slots = [None] * self.size
def hash_function(self, key):
s = str(key)
n_hash = 0
for obj in s:
if obj.isdigit():
n_hash = (n_hash << 5) + n_hash + ord(obj)
return n_hash % self.size
def quad_prob(self, oldhash, iter):
n_hash = 0
n_hash = (oldhash + iter**2) % self.size
return n_hash
def put(self, key):
collis_count = 0
hashval = self.hash_function(key)
if self.slots[hashval] == None:
self.slots[hashval] = key
else:
if self.slots[hashval] == key:
pass
else:
iter_count = 1
first_hash = hashval
nextslot = self.quad_prob(first_hash, iter_count)
# looking for a key or any empty slot
while self.slots[nextslot] != None and self.slots[nextslot] != key and iter_count <= self.size:
iter_count += 1
nextslot = self.quad_prob(first_hash, iter_count)
collis_count = iter_count
if self.slots[nextslot] == None:
self.slots[nextslot] = key
return collis_count

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