Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
MAP = [list(x) for x in MAP.split("\n") if x]
COSTS = {
"up": 1.0,
"down": 1.0,
"left": 1.0,
"right": 1.0,
"up left": 1.4,
"up right": 1.4,
"down left": 1.4,
"down right": 1.4,
}
class GameWalkPuzzle(SearchProblem):
def __init__(self, board):
self.board = board
self.goal = (0, 0)
for y in xrange(len(self.board)):
for x in xrange(len(self.board[y])):
if self.board[y][x].lower() == "o":
self.initial = (x, y)
elif self.board[y][x].lower() == "x":
self.goal = (x, y)
super(GameWalkPuzzle, self).__init__(initial_state=self.initial)
def actions(self, state):
actions = []
for action in COSTS.keys():
from simpleai.search import astar, SearchProblem
# Class containing methods to solve the puzzle
class PuzzleSolver(SearchProblem):
# Action method to get the list of the possible
# numbers that can be moved in to the empty space
def actions(self, cur_state):
rows = string_to_list(cur_state)
row_empty, col_empty = get_location(rows, 'e')
actions = []
if row_empty > 0:
actions.append(rows[row_empty - 1][col_empty])
if row_empty < 2:
actions.append(rows[row_empty + 1][col_empty])
if col_empty > 0:
actions.append(rows[row_empty][col_empty - 1])
if col_empty < 2:
actions.append(rows[row_empty][col_empty + 1])
# coding=utf-8
from simpleai.search import SearchProblem, astar
GOAL = 'HELLO WORLD'
class HelloProblem(SearchProblem):
def actions(self, state):
if len(state) < len(GOAL):
return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ')
else:
return []
def result(self, state, action):
return state + action
def is_goal(self, state):
return state == GOAL
def heuristic(self, state):
# how far are we from the goal?
wrong = sum([1 if state[i] != GOAL[i] else 0
for i in range(len(state))])
import argparse
import simpleai.search as ss
def build_arg_parser():
parser = argparse.ArgumentParser(description='Creates the input string \
using the greedy algorithm')
parser.add_argument("--input-string", dest="input_string", required=True,
help="Input string")
parser.add_argument("--initial-state", dest="initial_state", required=False,
default='', help="Starting point for the search")
return parser
class CustomProblem(ss.SearchProblem):
def set_target(self, target_string):
self.target_string = target_string
# Check the current state and take the right action
def actions(self, cur_state):
if len(cur_state) < len(self.target_string):
alphabets = 'abcdefghijklmnopqrstuvwxyz'
return list(alphabets + ' ' + alphabets.upper())
else:
return []
# Concatenate state and action to get the result
def result(self, cur_state, action):
return cur_state + action
# Check if goal has been achieved
import math
from simpleai.search import SearchProblem, astar
class ShortestPath(SearchProblem):
def __init__(self, size, start, end, obstacles):
self.size = size
self.start = start
self.end = end
self.obstacles = obstacles
super(ShortestPath, self).__init__(initial_state=self.start)
def actions(self, state):
(row, col) = state
(max_row, max_col) = self.size
succ_states = []
if row > 1:
succ_states += [(row-1, col)]
if col > 1:
succ_states += [(row, col-1)]
if row < max_row:
if `i == None` then `j` is not aligned to anything (is a gap).
if `j == None` then `i` is not aligned to anything (is a gap).
If `minimize` is `True` this function minimizes the sum of the weights
instead.
"""
if score is None:
score = self.score
if penalty is None:
penalty = self.penalty
problem = SequenceAlignmentSearchProblem(xs, ys, score, penalty)
node = astar(problem, graph_search=True)
path = [action for action, node in node.path()[1:]]
return path
class SequenceAlignmentSearchProblem(SearchProblem):
def __init__(self, xs, ys, weight, gap_penalty):
super(SequenceAlignmentSearchProblem, self).__init__((-1, -1))
self.xs = xs
self.ys = ys
self.W = weight
if gap_penalty < 0.0:
raise ValueError("gap penalty cannot be negative")
self.D = gap_penalty
self.N = len(xs)
self.M = len(ys)
self.goal = (self.N - 1, self.M - 1)
def actions(self, state):
i, j = state
i += 1
j += 1
import math
from simpleai.search import SearchProblem, astar
# Class containing the methods to solve the maze
class MazeSolver(SearchProblem):
# Initialize the class
def __init__(self, board):
self.board = board
self.goal = (0, 0)
for y in range(len(self.board)):
for x in range(len(self.board[y])):
if self.board[y][x].lower() == "o":
self.initial = (x, y)
elif self.board[y][x].lower() == "x":
self.goal = (x, y)
super(MazeSolver, self).__init__(initial_state=self.initial)
# Define the method that takes actions
# to arrive at the solution
Returns a tuple: row, column'''
for ir, row in enumerate(rows):
for ic, element in enumerate(row):
if element == element_to_find:
return ir, ic
# we create a cache for the goal position of each piece, so we don't have to
# recalculate them every time
goal_positions = {}
rows_goal = string_to_list(GOAL)
for number in '12345678e':
goal_positions[number] = find_location(rows_goal, number)
class EigthPuzzleProblem(SearchProblem):
def actions(self, state):
'''Returns a list of the pieces we can move to the empty space.'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
actions = []
if row_e > 0:
actions.append(rows[row_e - 1][col_e])
if row_e < 2:
actions.append(rows[row_e + 1][col_e])
if col_e > 0:
actions.append(rows[row_e][col_e - 1])
if col_e < 2:
actions.append(rows[row_e][col_e + 1])
return actions
if `i == None` then `j` is not aligned to anything (is a gap).
if `j == None` then `i` is not aligned to anything (is a gap).
If `minimize` is `True` this function minimizes the sum of the weights
instead.
"""
if score is None:
score = self.score
if penalty is None:
penalty = self.penalty
problem = SequenceAlignmentSearchProblem(xs, ys, score, penalty)
node = astar(problem, graph_search=True)
path = [action for action, node in node.path()[1:]]
return path
class SequenceAlignmentSearchProblem(SearchProblem):
"""
Represents and manipulates the search space for a sequence
alignment problem. Used by simpleai's graph search algorithm.
"""
def __init__(self, xs, ys, score, gap_penalty):
super(SequenceAlignmentSearchProblem, self).__init__((-1, -1))
self.xs = xs
self.ys = ys
self.W = score
if gap_penalty < 0.0:
raise ValueError("gap penalty cannot be negative")
self.D = gap_penalty
self.N = len(xs)
self.M = len(ys)
self.goal = (self.N - 1, self.M - 1)
# coding=utf-8
from simpleai.search import SearchProblem, astar
class MissionersProblem(SearchProblem):
'''Missioners and cannibals problem.'''
def __init__(self):
super(MissionersProblem, self).__init__(initial_state=(3, 3, 0))
# each action has a printable text, and the number of missioners
# and cannibals to move on that action
self._actions = [('1c', (0,1)),
('1m', (1, 0)),
('2c', (0, 2)),
('2m', (2, 0)),
('1m1c', (1, 1))]
def actions(self, s):
'''Possible actions from a state.'''
# we try to generate every possible state and then filter those
# states that are valid