Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Fix flake8 warnings #119

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 11, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 18 additions & 14 deletions agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@
#
# Speed control in GUI does not have any effect -- fix it.

from utils import *
from utils import * # noqa

import random
import copy
import collections

#______________________________________________________________________________
# ______________________________________________________________________________


class Thing(object):
Expand All @@ -51,7 +51,8 @@ class Thing(object):
.__name__ slot (used for output only)."""

def __repr__(self):
return '<{}>'.format(getattr(self, '__name__', self.__class__.__name__))
return '<{}>'.format(getattr(self, '__name__',
self.__class__.__name__))

def is_alive(self):
"Things that are 'alive' should return true."
Expand Down Expand Up @@ -108,7 +109,7 @@ def new_program(percept):
agent.program = new_program
return agent

#______________________________________________________________________________
# ______________________________________________________________________________


def TableDrivenAgentProgram(table):
Expand All @@ -129,7 +130,7 @@ def RandomAgentProgram(actions):
"An agent that chooses an action at random, ignoring all percepts."
return lambda percept: random.choice(actions)

#______________________________________________________________________________
# ______________________________________________________________________________


def SimpleReflexAgentProgram(rules, interpret_input):
Expand Down Expand Up @@ -159,7 +160,7 @@ def rule_match(state, rules):
if rule.matches(state):
return rule

#______________________________________________________________________________
# ______________________________________________________________________________

loc_A, loc_B = (0, 0), (1, 0) # The two locations for the Vacuum world

Expand Down Expand Up @@ -214,7 +215,7 @@ def program(location, status):
return 'Left'
return Agent(program)

#______________________________________________________________________________
# ______________________________________________________________________________


class Environment(object):
Expand All @@ -237,7 +238,10 @@ def thing_classes(self):
return [] # List of classes that can go into environment

def percept(self, agent):
"Return the percept that the agent sees at this point. (Implement this.)"
'''
Return the percept that the agent sees at this point.
(Implement this.)
'''
raise NotImplementedError

def execute_action(self, agent, action):
Expand Down Expand Up @@ -305,7 +309,8 @@ def delete_thing(self, thing):
except(ValueError, e):
print(e)
print(" in Environment delete_thing")
print(" Thing to be removed: {} at {}" .format(thing, thing.location))
print(" Thing to be removed: {} at {}" .format(thing,
thing.location))
print(" from list: {}" .format([(thing, thing.location)
for thing in self.things]))
if thing in self.agents:
Expand Down Expand Up @@ -419,7 +424,7 @@ class Obstacle(Thing):
class Wall(Obstacle):
pass

#______________________________________________________________________________
# ______________________________________________________________________________
# Vacuum environment


Expand Down Expand Up @@ -502,7 +507,7 @@ def default_location(self, thing):
"Agents start in either location at random."
return random.choice([loc_A, loc_B])

#______________________________________________________________________________
# ______________________________________________________________________________
# The Wumpus World


Expand Down Expand Up @@ -538,7 +543,7 @@ def thing_classes(self):
# Needs a lot of work ...


#______________________________________________________________________________
# ______________________________________________________________________________

def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
"""See how well each of several agents do in n instances of an environment.
Expand All @@ -559,7 +564,7 @@ def score(env):
return agent.performance
return mean(list(map(score, envs)))

#_________________________________________________________________________
# _________________________________________________________________________

__doc__ += """
>>> a = ReflexVacuumAgent()
Expand Down Expand Up @@ -590,4 +595,3 @@ def score(env):
>>> 0.5 < testv(RandomVacuumAgent) < 3
True
"""

55 changes: 31 additions & 24 deletions csp.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
"""CSP (Constraint Satisfaction Problems) problems and solvers. (Chapter 6)."""

from utils import *
from utils import * # noqa
import search

from collections import defaultdict
from functools import reduce

import itertools
import re


class CSP(search.Problem):

Expand Down Expand Up @@ -44,7 +47,8 @@ class CSP(search.Problem):
display(a) Print a human-readable representation

>>> search.depth_first_graph_search(australia)
<Node (('WA', 'B'), ('Q', 'B'), ('T', 'B'), ('V', 'B'), ('SA', 'G'), ('NT', 'R'), ('NSW', 'R'))>
<Node (('WA', 'B'), ('Q', 'B'), ('T', 'B'), ('V', 'B'), ('SA', 'G'),
('NT', 'R'), ('NSW', 'R'))>
"""

def __init__(self, vars, domains, neighbors, constraints):
Expand All @@ -70,8 +74,8 @@ def nconflicts(self, var, val, assignment):
"Return the number of conflicts var=val has with other variables."
# Subclasses may implement this more efficiently
def conflict(var2):
return (var2 in assignment
and not self.constraints(var, val, var2, assignment[var2]))
return (var2 in assignment and
not self.constraints(var, val, var2, assignment[var2]))
return count_if(conflict, self.neighbors[var])

def display(self, assignment):
Expand Down Expand Up @@ -149,7 +153,7 @@ def conflicted_vars(self, current):
return [var for var in self.vars
if self.nconflicts(var, current[var], current) > 0]

#______________________________________________________________________________
# ______________________________________________________________________________
# Constraint Propagation with AC-3


Expand Down Expand Up @@ -180,7 +184,7 @@ def revise(csp, Xi, Xj, removals):
revised = True
return revised

#______________________________________________________________________________
# ______________________________________________________________________________
# CSP Backtracking Search

# Variable ordering
Expand Down Expand Up @@ -251,17 +255,21 @@ def backtracking_search(csp,
"""[Fig. 6.5]
>>> backtracking_search(australia) is not None
True
>>> backtracking_search(australia, select_unassigned_variable=mrv) is not None
>>> backtracking_search(australia,
>>> select_unassigned_variable=mrv) is not None
True
>>> backtracking_search(australia, order_domain_values=lcv) is not None
>>> backtracking_search(australia,
>>> order_domain_values=lcv) is not None
True
>>> backtracking_search(australia, select_unassigned_variable=mrv, order_domain_values=lcv) is not None
>>> backtracking_search(australia, select_unassigned_variable=mrv,
>>> order_domain_values=lcv) is not None
True
>>> backtracking_search(australia, inference=forward_checking) is not None
True
>>> backtracking_search(australia, inference=mac) is not None
True
>>> backtracking_search(usa, select_unassigned_variable=mrv, order_domain_values=lcv, inference=mac) is not None
>>> backtracking_search(usa, select_unassigned_variable=mrv,
>>> order_domain_values=lcv, inference=mac) is not None
True
"""

Expand All @@ -285,7 +293,7 @@ def backtrack(assignment):
assert result is None or csp.goal_test(result)
return result

#______________________________________________________________________________
# ______________________________________________________________________________
# Min-conflicts hillclimbing search for CSPs


Expand Down Expand Up @@ -313,12 +321,11 @@ def min_conflicts_value(csp, var, current):
return argmin_random_tie(csp.domains[var],
lambda val: csp.nconflicts(var, val, current))

#______________________________________________________________________________
# ______________________________________________________________________________


def tree_csp_solver(csp):
"[Fig. 6.11]"
n = len(csp.vars)
assignment = {}
root = csp.vars[0]
X, parent = topological_sort(csp.vars, root)
Expand All @@ -339,7 +346,7 @@ def topological_sort(xs, x):
def make_arc_consistent(Xj, Xk, csp):
unimplemented()

#______________________________________________________________________________
# ______________________________________________________________________________
# Map-Coloring Problems


Expand Down Expand Up @@ -417,7 +424,7 @@ def parse_neighbors(neighbors, vars=[]):
PI; PA: LR RA; PC: PL CE LI AQ; PI: NH NO CA IF; PL: BR NB CE PC; RA:
AU BO FC PA LR""")

#______________________________________________________________________________
# ______________________________________________________________________________
# n-Queens Problem


Expand Down Expand Up @@ -507,17 +514,14 @@ def display(self, assignment):
print(str(self.nconflicts(var, val, assignment))+ch, end=' ')
print()

#______________________________________________________________________________
# ______________________________________________________________________________
# Sudoku

import itertools
import re


def flatten(seqs): return sum(seqs, [])

easy1 = '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..'
harder1 = '4173698.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......'
easy1 = '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..' # noqa
harder1 = '4173698.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......' # noqa

_R3 = list(range(3))
_CELL = itertools.count().__next__
Expand All @@ -531,6 +535,7 @@ def flatten(seqs): return sum(seqs, [])
for v in unit:
_NEIGHBORS[v].update(unit - set([v]))


class Sudoku(CSP):

"""A Sudoku problem.
Expand Down Expand Up @@ -564,7 +569,8 @@ class Sudoku(CSP):
8 1 4 | 2 5 3 | 7 6 9
6 9 5 | 4 1 7 | 3 8 2
>>> h = Sudoku(harder1)
>>> None != backtracking_search(h, select_unassigned_variable=mrv, inference=forward_checking)
>>> None != backtracking_search(h, select_unassigned_variable=mrv,
>>> inference=forward_checking)
True
"""
R3 = _R3
Expand Down Expand Up @@ -596,8 +602,9 @@ def show_cell(cell): return str(assignment.get(cell, '.'))
def abut(lines1, lines2): return list(
map(' | '.join, list(zip(lines1, lines2))))
print('\n------+-------+------\n'.join(
'\n'.join(reduce(abut, list(map(show_box, brow)))) for brow in self.bgrid))
#______________________________________________________________________________
'\n'.join(reduce(
abut, list(map(show_box, brow)))) for brow in self.bgrid))
# ______________________________________________________________________________
# The Zebra Puzzle


Expand Down
13 changes: 7 additions & 6 deletions games.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""Games, or Adversarial Search. (Chapter 5)
"""

from utils import *
from utils import * # noqa

import random

#______________________________________________________________________________
# ______________________________________________________________________________
# Minimax Search


Expand Down Expand Up @@ -35,7 +35,7 @@ def min_value(state):
return argmax(game.actions(state),
lambda a: min_value(game.result(state, a)))

#______________________________________________________________________________
# ______________________________________________________________________________


def alphabeta_full_search(state, game):
Expand Down Expand Up @@ -105,11 +105,12 @@ def min_value(state, alpha, beta, depth):
# Body of alphabeta_search starts here:
# The default test cuts off at depth d or at a terminal state
cutoff_test = (cutoff_test or
(lambda state, depth: depth > d or game.terminal_test(state)))
(lambda state, depth: depth > d or
game.terminal_test(state)))
eval_fn = eval_fn or (lambda state: game.utility(state, player))
return max_value(state, -infinity, infinity, 0)

#______________________________________________________________________________
# ______________________________________________________________________________
# Players for Games


Expand Down Expand Up @@ -141,7 +142,7 @@ def play_game(game, *players):
if game.terminal_test(state):
return game.utility(state, game.to_move(game.initial))

#______________________________________________________________________________
# ______________________________________________________________________________
# Some Sample Games


Expand Down
Loading