From 18b816f57546c952fb4795b0aac6dc0694664a83 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 17:33:46 +0200 Subject: [PATCH 01/18] Update search.py Commenting issues fixed (spacing and punctuation was off sometimes). --- search.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/search.py b/search.py index 12a723662..2f0bd62ef 100644 --- a/search.py +++ b/search.py @@ -389,13 +389,14 @@ def simulated_annealing(problem, schedule=exp_schedule()): def and_or_graph_search(problem): - """Used when the environment is nondeterministic and completely observable - Contains OR nodes where the agent is free to choose any action + """Used when the environment is nondeterministic and completely observable. + Contains OR nodes where the agent is free to choose any action. After every action there is an AND node which contains all possible states - the agent may reach due to stochastic nature of environment - The agent must be able to handle all possible states of the AND node(as it - may end up in any of them) returns a conditional plan to reach goal state, - or failure if the former is not possible""" + the agent may reach due to stochastic nature of environment. + The agent must be able to handle all possible states of the AND node (as it + may end up in any of them). + Returns a conditional plan to reach goal state, + or failure if the former is not possible.""" "[Figure 4.11]" # functions used by and_or_search @@ -411,7 +412,7 @@ def or_search(state, problem, path): return [action, plan] def and_search(states, problem, path): - "returns plan in form of dictionary where we take action plan[s] if we reach state s" # noqa + "Returns plan in form of dictionary where we take action plan[s] if we reach state s." # noqa plan = {} for s in states: plan[s] = or_search(s, problem, path) @@ -497,7 +498,7 @@ def h(self, state): def c(self, s, a, s1): """ - Returns a cost estimate for an agent to move from state 's' to state 's1' + Returns a cost estimate for an agent to move from state 's' to state 's1'. """ return 1 @@ -516,7 +517,7 @@ class LRTAStarAgent: Abstract class for LRTA*-Agent. A problem needs to be provided which is an instanace of a subclass of Problem Class. - Takes a OnlineSearchProblem [Figure 4.23] as a problem + Takes a OnlineSearchProblem [Figure 4.23] as a problem. """ def __init__(self, problem): @@ -552,7 +553,7 @@ def __call__(self, s1): # as of now s1 is a state rather than a percept def LRTA_cost(self, s, a, s1, H): """ Returns cost to move from state 's' to state 's1' plus - estimated cost to get to goal from s1 + estimated cost to get to goal from s1. """ print(s, a, s1) if s1 is None: @@ -817,10 +818,10 @@ def h(self, node): class GraphProblemStochastic(GraphProblem): """ A version of GraphProblem where an action can lead to - nondeterministic output i.e. multiple possible states + nondeterministic output i.e. multiple possible states. Define the graph as dict(A = dict(Action = [[, , ...], ], ...), ...) - A the dictionary format is different, make sure the graph is created as a directed graph + A the dictionary format is different, make sure the graph is created as a directed graph. """ def result(self, state, action): @@ -1006,7 +1007,7 @@ def __len__(self): class BoggleFinder: - """A class that allows you to find all the words in a Boggle board. """ + """A class that allows you to find all the words in a Boggle board.""" wordlist = None # A class variable, holding a wordlist From c3d76de93ff070dc0a126a93ca59db6831d5169b Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 17:42:52 +0200 Subject: [PATCH 02/18] Update agents.py --- agents.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/agents.py b/agents.py index 21dedaa15..d2fc19521 100644 --- a/agents.py +++ b/agents.py @@ -329,7 +329,7 @@ class Direction(): To change directions: d = d + "right" or d = d + Direction.R #Both do the same thing Note that the argument to __add__ must be a string and not a Direction object. - Also, it (the argument) can only be right or left. ''' + Also, it (the argument) can only be right or left.''' R = "right" L = "left" @@ -428,8 +428,8 @@ def default_location(self, thing): return (random.choice(self.width), random.choice(self.height)) def move_to(self, thing, destination): - '''Move a thing to a new location. Returns True on success or False if there is an Obstacle - If thing is grabbing anything, they move with him ''' + '''Move a thing to a new location. Returns True on success or False if there is an Obstacle. + If thing is holding anything, they move with him.''' thing.bump = self.some_things_at(destination, Obstacle) if not thing.bump: thing.location = destination @@ -451,7 +451,7 @@ def move_to(self, thing, destination): def add_thing(self, thing, location=(1, 1), exclude_duplicate_class_items=False): '''Adds things to the world. If (exclude_duplicate_class_items) then the item won't be added if the location - has at least one item of the same class''' + has at least one item of the same class.''' if (self.is_inbounds(location)): if (exclude_duplicate_class_items and any(isinstance(t, thing.__class__) for t in self.list_things_at(location))): @@ -526,7 +526,7 @@ class Wall(Obstacle): # Continuous environment class ContinuousWorld(Environment): - """ Model for Continuous World. """ + """ Model for Continuous World.""" def __init__(self, width=10, height=10): super(ContinuousWorld, self).__init__() self.width = width @@ -538,7 +538,7 @@ def add_obstacle(self, coordinates): class PolygonObstacle(Obstacle): def __init__(self, coordinates): - """ Coordinates is a list of tuples. """ + """ Coordinates is a list of tuples.""" super(PolygonObstacle, self).__init__() self.coordinates = coordinates @@ -715,7 +715,7 @@ def init_world(self, program): self.add_thing(Explorer(program), (1, 1), True) def get_world(self, show_walls=True): - '''returns the items in the world''' + '''Returns the items in the world''' result = [] x_start, y_start = (0, 0) if show_walls else (1, 1) x_end, y_end = (self.width, self.height) if show_walls else (self.width - 1, self.height - 1) @@ -765,8 +765,8 @@ def percept(self, agent): return result def execute_action(self, agent, action): - '''Modify the state of the environment based on the agent's actions - Performance score taken directly out of the book''' + '''Modify the state of the environment based on the agent's actions. + Performance score taken directly out of the book.''' if isinstance(agent, Explorer) and self.in_danger(agent): return @@ -818,7 +818,7 @@ def in_danger(self, agent): def is_done(self): '''The game is over when the Explorer is killed - or if he climbs out of the cave only at (1,1)''' + or if he climbs out of the cave only at (1,1).''' explorer = [agent for agent in self.agents if isinstance(agent, Explorer) ] if len(explorer): if explorer[0].alive: From fc7ff73a76b6e84ec23767351f0b4677cecd839b Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 17:44:15 +0200 Subject: [PATCH 03/18] Update canvas.py Grammar --- canvas.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/canvas.py b/canvas.py index 4ad780380..213e38cc9 100644 --- a/canvas.py +++ b/canvas.py @@ -12,8 +12,8 @@ class Canvas: """Inherit from this class to manage the HTML canvas element in jupyter notebooks. To create an object of this class any_name_xyz = Canvas("any_name_xyz") - The first argument given must be the name of the object being create - IPython must be able to refernce the variable name that is being passed + The first argument given must be the name of the object being created. + IPython must be able to refernce the variable name that is being passed. """ def __init__(self, varname, id=None, width=800, height=600): From 48faa2b057a020a857e6e254464f536ea15b3442 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 17:47:21 +0200 Subject: [PATCH 04/18] Update grid.py --- grid.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grid.py b/grid.py index 0fb0efe9d..4400d217b 100644 --- a/grid.py +++ b/grid.py @@ -1,6 +1,6 @@ # OK, the following are not as widely useful utilities as some of the other # functions here, but they do show up wherever we have 2D grids: Wumpus and -# Vacuum worlds, TicTacToe and Checkers, and markov decision Processes. +# Vacuum worlds, TicTacToe and Checkers, and Markov Decision Processes. # __________________________________________________________________________ import math From 3732f5e14d0005f969d8d975e9fe92adcfb9fec1 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 17:53:18 +0200 Subject: [PATCH 05/18] Update learning.py Added period --- learning.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/learning.py b/learning.py index 5db41efa5..18bd7bb93 100644 --- a/learning.py +++ b/learning.py @@ -826,7 +826,7 @@ def cross_validation_wrapper(learner, dataset, k=10, trials=1): """ Fig 18.8 Return the optimal value of size having minimum error - on validataion set + on validataion set. err_train: a training error array, indexed by size err_val: a validataion error array, indexed by size """ From 402c0b14efccde1de43ba0c23fbd5fcc38bd6111 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 17:56:10 +0200 Subject: [PATCH 06/18] Update logic.py Fix quoting --- logic.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/logic.py b/logic.py index 8b5e8bf8e..338e5aac2 100644 --- a/logic.py +++ b/logic.py @@ -670,7 +670,7 @@ def sat_count(sym): class HybridWumpusAgent(agents.Agent): - "An agent for the wumpus world that does logical inference. [Figure 7.20]""" + """An agent for the wumpus world that does logical inference. [Figure 7.20]""" def __init__(self): raise NotImplementedError @@ -789,7 +789,7 @@ def unify(x, y, s): def is_variable(x): - "A variable is an Expr with no args and a lowercase symbol as the op." + """A variable is an Expr with no args and a lowercase symbol as the op.""" return isinstance(x, Expr) and not x.args and x.op[0].islower() @@ -819,7 +819,7 @@ def occur_check(var, x, s): def extend(s, var, val): - "Copy the substitution s and extend it by setting var to val; return copy." + """Copy the substitution s and extend it by setting var to val; return copy.""" s2 = s.copy() s2[var] = val return s2 @@ -932,7 +932,7 @@ def fetch_rules_for_goal(self, goal): def fol_bc_ask(KB, query): """A simple backward-chaining algorithm for first-order logic. [Figure 9.6] - KB should be an instance of FolKB, and query an atomic sentence. """ + KB should be an instance of FolKB, and query an atomic sentence.""" return fol_bc_or(KB, query, {}) @@ -995,7 +995,7 @@ def diff(y, x): def simp(x): - "Simplify the expression x." + """Simplify the expression x.""" if isnumber(x) or not x.args: return x args = list(map(simp, x.args)) @@ -1058,5 +1058,5 @@ def simp(x): def d(y, x): - "Differentiate and then simplify." + """Differentiate and then simplify.""" return simp(diff(y, x)) From 95f44ddb47c8ef0a7c46d2a66d0ca7280c32f0ef Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 17:57:02 +0200 Subject: [PATCH 07/18] Update mdp.py Fixed quoting --- mdp.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mdp.py b/mdp.py index 8b0714da9..2854d0616 100644 --- a/mdp.py +++ b/mdp.py @@ -80,7 +80,7 @@ def T(self, state, action): (0.1, self.go(state, turn_left(action)))] def go(self, state, direction): - "Return the state that results from going in this direction." + """Return the state that results from going in this direction.""" state1 = vector_add(state, direction) return state1 if state1 in self.states else state @@ -110,7 +110,7 @@ def to_arrows(self, policy): def value_iteration(mdp, epsilon=0.001): - "Solving an MDP by value iteration. [Figure 17.4]" + """Solving an MDP by value iteration. [Figure 17.4]""" U1 = {s: 0 for s in mdp.states} R, T, gamma = mdp.R, mdp.T, mdp.gamma while True: @@ -134,14 +134,14 @@ def best_policy(mdp, U): def expected_utility(a, s, U, mdp): - "The expected utility of doing a in state s, according to the MDP and U." + """The expected utility of doing a in state s, according to the MDP and U.""" return sum([p * U[s1] for (p, s1) in mdp.T(s, a)]) # ______________________________________________________________________________ def policy_iteration(mdp): - "Solve an MDP by policy iteration [Figure 17.7]" + """Solve an MDP by policy iteration [Figure 17.7]""" U = {s: 0 for s in mdp.states} pi = {s: random.choice(mdp.actions(s)) for s in mdp.states} while True: From 2c5c309f833fdc2bf40b1b37c313a40fe95234ce Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 17:58:34 +0200 Subject: [PATCH 08/18] Update nlp.py Capitalization and punctuation fixes --- nlp.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nlp.py b/nlp.py index 7273b98da..3c95e961d 100644 --- a/nlp.py +++ b/nlp.py @@ -34,7 +34,7 @@ def Lexicon(**rules): class Grammar: def __init__(self, name, rules, lexicon): - "A grammar has a set of rules and a lexicon." + """A grammar has a set of rules and a lexicon.""" self.name = name self.rules = rules self.lexicon = lexicon @@ -44,11 +44,11 @@ def __init__(self, name, rules, lexicon): self.categories[word].append(lhs) def rewrites_for(self, cat): - "Return a sequence of possible rhs's that cat can be rewritten as." + """Return a sequence of possible rhs's that cat can be rewritten as.""" return self.rules.get(cat, ()) def isa(self, word, cat): - "Return True iff word is of category cat" + """Return True iff word is of category cat""" return cat in self.categories[word] def __repr__(self): @@ -293,8 +293,8 @@ def expand_pages( pages ): return expanded def relevant_pages(query): - """relevant pages are pages that contain the query in its entireity. - If a page's content contains the query it is returned by the function""" + """Relevant pages are pages that contain the query in its entireity. + If a page's content contains the query it is returned by the function.""" relevant = {} print("pagesContent in function: ", pagesContent) for addr, page in pagesIndex.items(): From 97c6f6d05e39e2f43e0173701d869d823c6a9ebd Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 18:00:09 +0200 Subject: [PATCH 09/18] Update planning.py --- planning.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/planning.py b/planning.py index 2dd57787a..3899c4534 100644 --- a/planning.py +++ b/planning.py @@ -7,9 +7,9 @@ class PDLL: """ - PDLL used to define a search problem - It stores states in a knowledge base consisting of first order logic statements - The conjunction of these logical statements completely define a state + PDLL used to define a search problem. + It stores states in a knowledge base consisting of first order logic statements. + The conjunction of these logical statements completely defines a state. """ def __init__(self, initial_state, actions, goal_test): @@ -22,7 +22,7 @@ def goal_test(self): def act(self, action): """ - Performs the action given as argument + Performs the action given as argument. Note that action is an Expr like expr('Remove(Glass, Table)') or expr('Eat(Sandwich)') """ action_name = action.op @@ -36,10 +36,10 @@ def act(self, action): class Action: """ - Defines an action schema using preconditions and effects - Use this to describe actions in PDDL - action is an Expr where variables are given as arguments(args) - Precondition and effect are both lists with positive and negated literals + Defines an action schema using preconditions and effects. + Use this to describe actions in PDDL. + action is an Expr where variables are given as arguments(args). + Precondition and effect are both lists with positive and negated literals. Example: precond_pos = [expr("Human(person)"), expr("Hungry(Person)")] precond_neg = [expr("Eaten(food)")] From c45b3be37bad161cbe0c50c1b32b648dd8011418 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 18:02:24 +0200 Subject: [PATCH 10/18] Update probability.py --- probability.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/probability.py b/probability.py index ed3aa5243..8a7fc4779 100644 --- a/probability.py +++ b/probability.py @@ -357,7 +357,7 @@ def pointwise_product(factors, bn): def sum_out(var, factors, bn): - "Eliminate var from all factors by summing over its values." + """Eliminate var from all factors by summing over its values.""" result, var_factors = [], [] for f in factors: (var_factors if var in f.variables else result).append(f) @@ -367,21 +367,21 @@ def sum_out(var, factors, bn): class Factor: - "A factor in a joint distribution." + """A factor in a joint distribution.""" def __init__(self, variables, cpt): self.variables = variables self.cpt = cpt def pointwise_product(self, other, bn): - "Multiply two factors, combining their variables." + """Multiply two factors, combining their variables.""" variables = list(set(self.variables) | set(other.variables)) cpt = {event_values(e, variables): self.p(e) * other.p(e) for e in all_events(variables, bn, {})} return Factor(variables, cpt) def sum_out(self, var, bn): - "Make a factor eliminating var by summing over its values." + """Make a factor eliminating var by summing over its values.""" variables = [X for X in self.variables if X != var] cpt = {event_values(e, variables): sum(self.p(extend(e, var, val)) for val in bn.variable_values(var)) @@ -389,18 +389,18 @@ def sum_out(self, var, bn): return Factor(variables, cpt) def normalize(self): - "Return my probabilities; must be down to one variable." + """Return my probabilities; must be down to one variable.""" assert len(self.variables) == 1 return ProbDist(self.variables[0], {k: v for ((k,), v) in self.cpt.items()}) def p(self, e): - "Look up my value tabulated for e." + """Look up my value tabulated for e.""" return self.cpt[event_values(e, self.variables)] def all_events(variables, bn, e): - "Yield every way of extending e with values for all variables." + """Yield every way of extending e with values for all variables.""" if not variables: yield e else: @@ -453,7 +453,7 @@ def rejection_sampling(X, e, bn, N): def consistent_with(event, evidence): - "Is event consistent with the given evidence?" + """Is event consistent with the given evidence?""" return all(evidence.get(k, v) == v for k, v in event.items()) @@ -527,7 +527,7 @@ def markov_blanket_sample(X, e, bn): class HiddenMarkovModel: - """ A Hidden markov model which takes Transition model and Sensor model as inputs""" + """A Hidden markov model which takes Transition model and Sensor model as inputs""" def __init__(self, transition_model, sensor_model, prior=[0.5, 0.5]): self.transition_model = transition_model From b82b0ccf0808eb31d3129dd28705d964596ccac1 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 18:03:59 +0200 Subject: [PATCH 11/18] Update rl.py 'th' to 'the' --- rl.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/rl.py b/rl.py index 97bb313a0..5241710fe 100644 --- a/rl.py +++ b/rl.py @@ -24,7 +24,7 @@ def __init__(self, init, actlist, terminals, gamma, states): def T(self, s, a): """Returns a list of tuples with probabilities for states - based on the learnt model P. """ + based on the learnt model P.""" return [(prob, res) for (res, prob) in self.P[(s, a)].items()] def __init__(self, pi, mdp): @@ -62,7 +62,7 @@ def __call__(self, percept): def update_state(self, percept): ''' To be overridden in most cases. The default case - assumes th percept to be of type (state, reward)''' + assumes the percept to be of type (state, reward)''' return percept @@ -70,7 +70,7 @@ class PassiveTDAgent: """The abstract class for a Passive (non-learning) agent that uses temporal differences to learn utility estimates. Override update_state method to convert percept to state and reward. The mdp being provided - should be an instance of a subclass of the MDP Class.[Figure 21.4] + should be an instance of a subclass of the MDP Class. [Figure 21.4] """ def __init__(self, pi, mdp, alpha=None): @@ -106,7 +106,7 @@ def __call__(self, percept): def update_state(self, percept): ''' To be overridden in most cases. The default case - assumes th percept to be of type (state, reward)''' + assumes the percept to be of type (state, reward)''' return percept From 81e980b74e0d6de5a627cdbe78c0cf53b5d0ba67 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 18:06:53 +0200 Subject: [PATCH 12/18] Update search.py --- search.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/search.py b/search.py index 2f0bd62ef..8985cfdc7 100644 --- a/search.py +++ b/search.py @@ -789,25 +789,25 @@ def distance_to_node(n): class GraphProblem(Problem): - "The problem of searching a graph from one node to another." + """The problem of searching a graph from one node to another.""" def __init__(self, initial, goal, graph): Problem.__init__(self, initial, goal) self.graph = graph def actions(self, A): - "The actions at a graph node are just its neighbors." + """The actions at a graph node are just its neighbors.""" return list(self.graph.get(A).keys()) def result(self, state, action): - "The result of going to a neighbor is just that neighbor." + """The result of going to a neighbor is just that neighbor.""" return action def path_cost(self, cost_so_far, A, action, B): return cost_so_far + (self.graph.get(A, B) or infinity) def h(self, node): - "h function is straight-line distance from a node's state to goal." + """h function is straight-line distance from a node's state to goal.""" locs = getattr(self.graph, 'locations', None) if locs: return int(distance(locs[node.state], locs[self.goal])) @@ -850,7 +850,7 @@ def __init__(self, N): self.initial = [None] * N def actions(self, state): - "In the leftmost empty column, try all non-conflicting rows." + """In the leftmost empty column, try all non-conflicting rows.""" if state[-1] is not None: return [] # All columns filled; no successors else: @@ -859,26 +859,26 @@ def actions(self, state): if not self.conflicted(state, row, col)] def result(self, state, row): - "Place the next queen at the given row." + """Place the next queen at the given row.""" col = state.index(None) new = state[:] new[col] = row return new def conflicted(self, state, row, col): - "Would placing a queen at (row, col) conflict with anything?" + """Would placing a queen at (row, col) conflict with anything?""" return any(self.conflict(row, col, state[c], c) for c in range(col)) def conflict(self, row1, col1, row2, col2): - "Would putting two queens in (row1, col1) and (row2, col2) conflict?" + """Would putting two queens in (row1, col1) and (row2, col2) conflict?""" return (row1 == row2 or # same row col1 == col2 or # same column row1 - col1 == row2 - col2 or # same \ diagonal row1 + col1 == row2 + col2) # same / diagonal def goal_test(self, state): - "Check if all columns filled, no conflicts." + """Check if all columns filled, no conflicts.""" if state[-1] is None: return False return not any(self.conflicted(state, state[col], col) @@ -910,7 +910,7 @@ def random_boggle(n=4): def print_boggle(board): - "Print the board in a 2-d array." + """Print the board in a 2-d array.""" n2 = len(board) n = exact_sqrt(n2) for i in range(n2): @@ -958,7 +958,7 @@ def boggle_neighbors(n2, cache={}): def exact_sqrt(n2): - "If n2 is a perfect square, return its square root, else raise error." + """If n2 is a perfect square, return its square root, else raise error.""" n = int(math.sqrt(n2)) assert n * n == n2 return n From 9ba524ca9c8bd01193af6bf4a3d8d4f526ec252e Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 18:08:15 +0200 Subject: [PATCH 13/18] Update text.py --- text.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/text.py b/text.py index 57a19d2ab..855e89aaf 100644 --- a/text.py +++ b/text.py @@ -153,17 +153,17 @@ def query(self, query_text, n=10): return heapq.nlargest(n, ((self.total_score(qwords, docid), docid) for docid in docids)) def score(self, word, docid): - "Compute a score for this word on the document with this docid." + """Compute a score for this word on the document with this docid.""" # There are many options; here we take a very simple approach return (log(1 + self.index[word][docid]) / log(1 + self.documents[docid].nwords)) def total_score(self, words, docid): - "Compute the sum of the scores of these words on the document with this docid." + """Compute the sum of the scores of these words on the document with this docid.""" return sum(self.score(word, docid) for word in words) def present(self, results): - "Present the results as a list." + """Present the results as a list.""" for (score, docid) in results: doc = self.documents[docid] print( @@ -171,7 +171,7 @@ def present(self, results): doc.title[:45].expandtabs()))) def present_results(self, query_text, n=10): - "Get results for the query and present them." + """Get results for the query and present them.""" self.present(self.query(query_text, n)) @@ -264,7 +264,7 @@ def maketrans(from_, to_): def encode(plaintext, code): - "Encodes text, using a code which is a permutation of the alphabet." + """Encodes text, using a code which is a permutation of the alphabet.""" trans = maketrans(alphabet + alphabet.upper(), code + code.upper()) return translate(plaintext, trans) @@ -293,7 +293,7 @@ def __init__(self, training_text): self.P2 = CountingProbDist(bigrams(training_text), default=1) def score(self, plaintext): - "Return a score for text based on how common letters pairs are." + """Return a score for text based on how common letters pairs are.""" s = 1.0 for bi in bigrams(plaintext): @@ -302,7 +302,7 @@ def score(self, plaintext): return s def decode(self, ciphertext): - "Return the shift decoding of text with the best score." + """Return the shift decoding of text with the best score.""" list_ = [(self.score(shift), shift) for shift in all_shifts(ciphertext)] @@ -310,7 +310,7 @@ def decode(self, ciphertext): def all_shifts(text): - "Return a list of all 26 possible encodings of text by a shift cipher." + """Return a list of all 26 possible encodings of text by a shift cipher.""" yield from (shift_encode(text, i) for i, _ in enumerate(alphabet)) @@ -339,7 +339,7 @@ def __init__(self, training_text, ciphertext=None): self.P2 = NgramTextModel(2, training_text) # By letter pair def decode(self, ciphertext): - "Search for a decoding of the ciphertext." + """Search for a decoding of the ciphertext.""" self.ciphertext = ciphertext problem = PermutationDecoderProblem(decoder=self) return search.best_first_tree_search( @@ -368,5 +368,5 @@ def actions(self, state): succs = [extend(state, plainchar, cipherchar)] # ???? # noqa def goal_test(self, state): - "We're done when we get all 26 letters assigned." + """We're done when we get all 26 letters assigned.""" return len(state) >= 26 From a54c561c372e1438dd585e3df5aca807e8527be5 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 18:09:57 +0200 Subject: [PATCH 14/18] Update utils.py --- utils.py | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/utils.py b/utils.py index 4ef7e0c08..54fc01ad3 100644 --- a/utils.py +++ b/utils.py @@ -14,7 +14,7 @@ def sequence(iterable): - "Coerce iterable to sequence, if it is not already one." + """Coerce iterable to sequence, if it is not already one.""" return (iterable if isinstance(iterable, collections.abc.Sequence) else tuple(iterable)) @@ -46,7 +46,7 @@ def product(numbers): def first(iterable, default=None): - "Return the first element of an iterable or the next element of a generator; or default." + """Return the first element of an iterable or the next element of a generator; or default.""" try: return iterable[0] except IndexError: @@ -74,12 +74,12 @@ def argmin_random_tie(seq, key=identity): def argmax_random_tie(seq, key=identity): - "Return an element with highest fn(seq[i]) score; break ties at random." + """Return an element with highest fn(seq[i]) score; break ties at random.""" return argmax(shuffled(seq), key=key) def shuffled(iterable): - "Randomly shuffle a copy of iterable." + """Randomly shuffle a copy of iterable.""" items = list(iterable) random.shuffle(items) return items @@ -184,7 +184,7 @@ def inverse_matrix(X): def probability(p): - "Return true with probability p." + """Return true with probability p.""" return p > random.uniform(0.0, 1.0) @@ -198,7 +198,7 @@ def weighted_sample_with_replacement(seq, weights, n): def weighted_sampler(seq, weights): - "Return a random-sample function that picks from seq weighted by weights." + """Return a random-sample function that picks from seq weighted by weights.""" totals = [] for w in weights: totals.append(w + totals[-1] if totals else w) @@ -207,7 +207,7 @@ def weighted_sampler(seq, weights): def rounder(numbers, d=4): - "Round a single number, or sequence of numbers, to d decimal places." + """Round a single number, or sequence of numbers, to d decimal places.""" if isinstance(numbers, (int, float)): return round(numbers, d) else: @@ -258,7 +258,7 @@ def step(x): from math import isclose except ImportError: def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): - "Return true if numbers a and b are close to each other." + """Return true if numbers a and b are close to each other.""" return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) # ______________________________________________________________________________ @@ -292,19 +292,19 @@ def memoized_fn(*args): def name(obj): - "Try to find some reasonable name for the object." + """Try to find some reasonable name for the object.""" return (getattr(obj, 'name', 0) or getattr(obj, '__name__', 0) or getattr(getattr(obj, '__class__', 0), '__name__', 0) or str(obj)) def isnumber(x): - "Is x a number?" + """Is x a number?""" return hasattr(x, '__int__') def issequence(x): - "Is x a sequence?" + """Is x a sequence?""" return isinstance(x, collections.abc.Sequence) @@ -332,7 +332,7 @@ def print_table(table, header=None, sep=' ', numfmt='%g'): def AIMAFile(components, mode='r'): - "Open a file based at the AIMA root directory." + """Open a file based at the AIMA root directory.""" aima_root = os.path.dirname(__file__) aima_file = os.path.join(aima_root, *components) @@ -436,17 +436,17 @@ def __repr__(self): def Symbol(name): - "A Symbol is just an Expr with no args." + """A Symbol is just an Expr with no args.""" return Expr(name) def symbols(names): - "Return a tuple of Symbols; names is a comma/whitespace delimited str." + """Return a tuple of Symbols; names is a comma/whitespace delimited str.""" return tuple(Symbol(name) for name in names.replace(',', ' ').split()) def subexpressions(x): - "Yield the subexpressions of an Expression (including x itself)." + """Yield the subexpressions of an Expression (including x itself).""" yield x if isinstance(x, Expr): for arg in x.args: @@ -454,7 +454,7 @@ def subexpressions(x): def arity(expression): - "The number of sub-expressions in this expression." + """The number of sub-expressions in this expression.""" if isinstance(expression, Expr): return len(expression.args) else: # expression is a number From de2f284cef83c28b37a84e899d54125fd1bad690 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 18:11:15 +0200 Subject: [PATCH 15/18] Update utils.py --- utils.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/utils.py b/utils.py index 54fc01ad3..a6c5d0bd5 100644 --- a/utils.py +++ b/utils.py @@ -217,8 +217,7 @@ def rounder(numbers, d=4): def num_or_str(x): """The argument is a string; convert to a number if - possible, or strip it. - """ + possible, or strip it.""" try: return int(x) except ValueError: @@ -379,7 +378,7 @@ def __floordiv__(self, rhs): return Expr('//', self, rhs) def __matmul__(self, rhs): return Expr('@', self, rhs) def __or__(self, rhs): - "Allow both P | Q, and P |'==>'| Q." + """Allow both P | Q, and P |'==>'| Q.""" if isinstance(rhs, Expression): return Expr('|', self, rhs) else: From 0e288a03fd368b5c4a80de5c89e80087d6472f6c Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 18:35:04 +0200 Subject: [PATCH 16/18] Update utils.py --- utils.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/utils.py b/utils.py index a6c5d0bd5..90d24d59f 100644 --- a/utils.py +++ b/utils.py @@ -217,7 +217,8 @@ def rounder(numbers, d=4): def num_or_str(x): """The argument is a string; convert to a number if - possible, or strip it.""" + possible, or strip it. + """ try: return int(x) except ValueError: From 1de5678ffc67521cab9ea351c849b28f4cf63040 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Wed, 1 Mar 2017 19:29:02 +0200 Subject: [PATCH 17/18] Update learning.py Typo --- learning.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/learning.py b/learning.py index 18bd7bb93..ce8871300 100644 --- a/learning.py +++ b/learning.py @@ -499,9 +499,9 @@ def __init__(self, weights=None, inputs=None): def network(input_units, hidden_layer_sizes, output_units): """ - Create of Directed Acyclic Network of given number layers + Create Directed Acyclic Network of given number layers. hidden_layers_sizes : list number of neuron units in each hidden layer - excluding input and output layers. + excluding input and output layers """ # Check for PerceptronLearner if hidden_layer_sizes: @@ -523,7 +523,7 @@ def network(input_units, hidden_layer_sizes, output_units): def BackPropagationLearner(dataset, net, learning_rate, epoches): - "[Figure 18.23] The back-propagation algorithm for multilayer network" + """[Figure 18.23] The back-propagation algorithm for multilayer network""" # Initialise weights for layer in net: for node in layer: From 66bcd806a4a3f94ef393c7eff10ec72117f36561 Mon Sep 17 00:00:00 2001 From: Antonis Maronikolakis Date: Thu, 2 Mar 2017 19:03:49 +0200 Subject: [PATCH 18/18] Update utils.py --- utils.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/utils.py b/utils.py index 90d24d59f..a6c5d0bd5 100644 --- a/utils.py +++ b/utils.py @@ -217,8 +217,7 @@ def rounder(numbers, d=4): def num_or_str(x): """The argument is a string; convert to a number if - possible, or strip it. - """ + possible, or strip it.""" try: return int(x) except ValueError: