Skip to content

Commit 4caca95

Browse files
Chipe1norvig
authored andcommittedMay 24, 2017
Fix flake8 warnings (aimacode#508)
* Fix flake8 warnings * Remove unnecessary #noqa * Fix doctest
1 parent e6d5fcf commit 4caca95

22 files changed

+76
-87
lines changed
 

‎.flake8

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
[flake8]
22
max-line-length = 100
3-
ignore = E121,E123,E126,E221,E222,E225,E226,E242,E701,E702,E704,E731,W503,F405
3+
ignore = E121,E123,E126,E221,E222,E225,E226,E242,E701,E702,E704,E731,W503,F405,F841
44
exclude = tests

‎agents.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,12 @@ def __init__(self, program=None):
8686
self.holding = []
8787
self.performance = 0
8888
if program is None or not isinstance(program, collections.Callable):
89-
print("Can't find a valid program for {}, falling back to default.".format(self.__class__.__name__))
89+
print("Can't find a valid program for {}, falling back to default.".format(
90+
self.__class__.__name__))
91+
9092
def program(percept):
9193
return eval(input('Percept={}; action? '.format(percept)))
94+
9295
self.program = program
9396

9497
def can_grab(self, thing):

‎canvas.py

+1
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ def update(self):
121121
self.exec_list = []
122122
display_html(exec_code)
123123

124+
124125
def display_html(html_string):
125126
from IPython.display import HTML, display
126127
display(HTML(html_string))

‎csp.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class CSP(search.Problem):
2020
the other variables that participate in constraints.
2121
constraints A function f(A, a, B, b) that returns true if neighbors
2222
A, B satisfy the constraint when they have values A=a, B=b
23-
23+
2424
In the textbook and in most mathematical definitions, the
2525
constraints are specified as explicit pairs of allowable values,
2626
but the formulation here is easier to express and more compact for
@@ -347,6 +347,7 @@ def topological_sort(X, root):
347347
build_topological(root, None, neighbors, visited, stack, parents)
348348
return stack, parents
349349

350+
350351
def build_topological(node, parent, neighbors, visited, stack, parents):
351352
"""Builds the topological sort and the parents of each node in the graph"""
352353
visited[node] = True
@@ -356,7 +357,7 @@ def build_topological(node, parent, neighbors, visited, stack, parents):
356357
build_topological(n, node, neighbors, visited, stack, parents)
357358

358359
parents[node] = parent
359-
stack.insert(0,node)
360+
stack.insert(0, node)
360361

361362

362363
def make_arc_consistent(Xj, Xk, csp):
@@ -533,10 +534,12 @@ def display(self, assignment):
533534
# Sudoku
534535

535536

536-
def flatten(seqs): return sum(seqs, [])
537+
def flatten(seqs):
538+
return sum(seqs, [])
539+
537540

538-
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
539-
harder1 = '4173698.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......' # noqa
541+
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..'
542+
harder1 = '4173698.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......'
540543

541544
_R3 = list(range(3))
542545
_CELL = itertools.count().__next__

‎learning.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,8 @@ def split_values_by_classes(self):
184184
target_names = self.values[self.target]
185185

186186
for v in self.examples:
187-
item = [a for a in v if a not in target_names] # Remove target from item
188-
buckets[v[self.target]].append(item) # Add item to bucket of its class
187+
item = [a for a in v if a not in target_names] # Remove target from item
188+
buckets[v[self.target]].append(item) # Add item to bucket of its class
189189

190190
return buckets
191191

@@ -199,7 +199,7 @@ def find_means_and_deviations(self):
199199
feature_numbers = len(self.inputs)
200200

201201
item_buckets = self.split_values_by_classes()
202-
202+
203203
means = defaultdict(lambda: [0 for i in range(feature_numbers)])
204204
deviations = defaultdict(lambda: [0 for i in range(feature_numbers)])
205205

@@ -216,7 +216,6 @@ def find_means_and_deviations(self):
216216

217217
return means, deviations
218218

219-
220219
def __repr__(self):
221220
return '<DataSet({}): {:d} examples, {:d} attributes>'.format(
222221
self.name, len(self.examples), len(self.attrs))
@@ -760,7 +759,6 @@ def LinearLearner(dataset, learning_rate=0.01, epochs=100):
760759
for i in range(len(w)):
761760
w[i] = w[i] + learning_rate * (dotproduct(err, X_col[i]) / num_examples)
762761

763-
764762
def predict(example):
765763
x = [1] + example
766764
return dotproduct(w, x)

‎logic.py

+11-27
Original file line numberDiff line numberDiff line change
@@ -845,23 +845,8 @@ def subst(s, x):
845845
return Expr(x.op, *[subst(s, arg) for arg in x.args])
846846

847847

848-
def fol_fc_ask(KB, alpha):
849-
"""A simple forward-chaining algorithm. [Figure 9.3]"""
850-
while new is not None:
851-
new = []
852-
for rule in KB:
853-
p, q = parse_definite_clause(standardize_variables(rule))
854-
for p_ in random.KB.clauses:
855-
if p != p_:
856-
for theta in (subst(theta, p) == subst(theta, p_)):
857-
q_ = subst(theta, q)
858-
if not unify(q_,KB.sentence in KB) or not unify(q_, new):
859-
new.append(q_)
860-
phi = unify(q_,alpha)
861-
if phi is not None:
862-
return phi
863-
KB.tell(new)
864-
return None
848+
def fol_fc_ask(KB, alpha): # TODO
849+
raise NotImplementedError
865850

866851

867852
def standardize_variables(sentence, dic=None):
@@ -936,16 +921,15 @@ def fetch_rules_for_goal(self, goal):
936921
]))
937922

938923
crime_kb = FolKB(
939-
map(expr,
940-
['(American(x) & Weapon(y) & Sells(x, y, z) & Hostile(z)) ==> Criminal(x)', # noqa
941-
'Owns(Nono, M1)',
942-
'Missile(M1)',
943-
'(Missile(x) & Owns(Nono, x)) ==> Sells(West, x, Nono)',
944-
'Missile(x) ==> Weapon(x)',
945-
'Enemy(x, America) ==> Hostile(x)',
946-
'American(West)',
947-
'Enemy(Nono, America)'
948-
]))
924+
map(expr, ['(American(x) & Weapon(y) & Sells(x, y, z) & Hostile(z)) ==> Criminal(x)',
925+
'Owns(Nono, M1)',
926+
'Missile(M1)',
927+
'(Missile(x) & Owns(Nono, x)) ==> Sells(West, x, Nono)',
928+
'Missile(x) ==> Weapon(x)',
929+
'Enemy(x, America) ==> Hostile(x)',
930+
'American(West)',
931+
'Enemy(Nono, America)'
932+
]))
949933

950934

951935
def fol_bc_ask(KB, query):

‎mdp.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
dictionary of {state:number} pairs. We then define the value_iteration
77
and policy_iteration algorithms."""
88

9-
from utils import argmax, vector_add, print_table # noqa
9+
from utils import argmax, vector_add
1010
from grid import orientations, turn_right, turn_left
1111

1212
import random
@@ -173,6 +173,8 @@ def policy_evaluation(pi, U, mdp, k=20):
173173
>>> sequential_decision_environment.to_arrows(pi)
174174
[['>', '>', '>', '.'], ['^', None, '^', '.'], ['^', '>', '^', '<']]
175175
176+
>>> from utils import print_table
177+
176178
>>> print_table(sequential_decision_environment.to_arrows(pi))
177179
> > > .
178180
^ None ^ .

‎nlp.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,16 @@ def __repr__(self):
5858
E0 = Grammar('E0',
5959
Rules( # Grammar for E_0 [Figure 22.4]
6060
S='NP VP | S Conjunction S',
61-
NP='Pronoun | Name | Noun | Article Noun | Digit Digit | NP PP | NP RelClause', # noqa
61+
NP='Pronoun | Name | Noun | Article Noun | Digit Digit | NP PP | NP RelClause',
6262
VP='Verb | VP NP | VP Adjective | VP PP | VP Adverb',
6363
PP='Preposition NP',
6464
RelClause='That VP'),
6565

6666
Lexicon( # Lexicon for E_0 [Figure 22.3]
67-
Noun="stench | breeze | glitter | nothing | wumpus | pit | pits | gold | east", # noqa
67+
Noun="stench | breeze | glitter | nothing | wumpus | pit | pits | gold | east",
6868
Verb="is | see | smell | shoot | fell | stinks | go | grab | carry | kill | turn | feel", # noqa
6969
Adjective="right | left | east | south | back | smelly",
70-
Adverb="here | there | nearby | ahead | right | left | east | south | back", # noqa
70+
Adverb="here | there | nearby | ahead | right | left | east | south | back",
7171
Pronoun="me | you | I | it",
7272
Name="John | Mary | Boston | Aristotle",
7373
Article="the | a | an",
@@ -166,7 +166,7 @@ def add_edge(self, edge):
166166
self.predictor(edge)
167167

168168
def scanner(self, j, word):
169-
"For each edge expecting a word of this category here, extend the edge." # noqa
169+
"For each edge expecting a word of this category here, extend the edge."
170170
for (i, j, A, alpha, Bb) in self.chart[j]:
171171
if Bb and self.grammar.isa(word, Bb[0]):
172172
self.add_edge([i, j+1, A, alpha + [(Bb[0], word)], Bb[1:]])
@@ -386,16 +386,18 @@ def __init__(self, address, hub=0, authority=0, inlinks=None, outlinks=None):
386386

387387
def HITS(query):
388388
"""The HITS algorithm for computing hubs and authorities with respect to a query."""
389-
pages = expand_pages(relevant_pages(query)) # in order to 'map' faithfully to pseudocode we
390-
for p in pages.values(): # won't pass the list of pages as an argument
389+
pages = expand_pages(relevant_pages(query))
390+
for p in pages.values():
391391
p.authority = 1
392392
p.hub = 1
393393
while True: # repeat until... convergence
394394
authority = {p: pages[p].authority for p in pages}
395395
hub = {p: pages[p].hub for p in pages}
396396
for p in pages:
397-
pages[p].authority = sum(hub[x] for x in getInlinks(pages[p])) # p.authority ← ∑i Inlinki(p).Hub
398-
pages[p].hub = sum(authority[x] for x in getOutlinks(pages[p])) # p.hub ← ∑i Outlinki(p).Authority
397+
# p.authority ← ∑i Inlinki(p).Hub
398+
pages[p].authority = sum(hub[x] for x in getInlinks(pages[p]))
399+
# p.hub ← ∑i Outlinki(p).Authority
400+
pages[p].hub = sum(authority[x] for x in getOutlinks(pages[p]))
399401
normalize(pages)
400402
if convergence():
401403
break

‎planning.py

+9-12
Original file line numberDiff line numberDiff line change
@@ -663,9 +663,8 @@ def act(self, action):
663663
if list_action is None:
664664
raise Exception("Action '{}' not found".format(action.name))
665665
list_action.do_action(self.jobs, self.resources, self.kb, args)
666-
# print(self.resources)
667-
668-
def refinements(hla, state, library): # TODO - refinements may be (multiple) HLA themselves ...
666+
667+
def refinements(hla, state, library): # TODO - refinements may be (multiple) HLA themselves ...
669668
"""
670669
state is a Problem, containing the current state kb
671670
library is a dictionary containing details for every possible refinement. eg:
@@ -709,39 +708,38 @@ def refinements(hla, state, library): # TODO - refinements may be (multiple) HLA
709708
}
710709
"""
711710
e = Expr(hla.name, hla.args)
712-
indices = [i for i,x in enumerate(library["HLA"]) if expr(x).op == hla.name]
711+
indices = [i for i, x in enumerate(library["HLA"]) if expr(x).op == hla.name]
713712
for i in indices:
714-
action = HLA(expr(library["steps"][i][0]), [ # TODO multiple refinements
713+
action = HLA(expr(library["steps"][i][0]), [ # TODO multiple refinements
715714
[expr(x) for x in library["precond_pos"][i]],
716715
[expr(x) for x in library["precond_neg"][i]]
717-
],
716+
],
718717
[
719718
[expr(x) for x in library["effect_pos"][i]],
720719
[expr(x) for x in library["effect_neg"][i]]
721720
])
722721
if action.check_precond(state.kb, action.args):
723722
yield action
724-
723+
725724
def hierarchical_search(problem, hierarchy):
726725
"""
727726
[Figure 11.5] 'Hierarchical Search, a Breadth First Search implementation of Hierarchical
728727
Forward Planning Search'
729-
730728
The problem is a real-world prodlem defined by the problem class, and the hierarchy is
731729
a dictionary of HLA - refinements (see refinements generator for details)
732730
"""
733731
act = Node(problem.actions[0])
734732
frontier = FIFOQueue()
735733
frontier.append(act)
736734
while(True):
737-
if not frontier: #(len(frontier)==0):
735+
if not frontier:
738736
return None
739737
plan = frontier.pop()
740738
print(plan.state.name)
741-
hla = plan.state #first_or_null(plan)
739+
hla = plan.state # first_or_null(plan)
742740
prefix = None
743741
if plan.parent:
744-
prefix = plan.parent.state.action #prefix, suffix = subseq(plan.state, hla)
742+
prefix = plan.parent.state.action # prefix, suffix = subseq(plan.state, hla)
745743
outcome = Problem.result(problem, prefix)
746744
if hla is None:
747745
if outcome.goal_test():
@@ -864,4 +862,3 @@ def goal_test(kb):
864862

865863
return Problem(init, [add_engine1, add_engine2, add_wheels1, add_wheels2, inspect1, inspect2],
866864
goal_test, [job_group1, job_group2], resources)
867-

‎search.py

+9-10
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@
66

77
from utils import (
88
is_in, argmin, argmax, argmax_random_tie, probability, weighted_sampler,
9-
weighted_sample_with_replacement, memoize, print_table, DataFile, Stack,
10-
FIFOQueue, PriorityQueue, name
9+
memoize, print_table, DataFile, Stack, FIFOQueue, PriorityQueue, name
1110
)
1211
from grid import distance
1312

@@ -419,7 +418,7 @@ def or_search(state, problem, path):
419418
return [action, plan]
420419

421420
def and_search(states, problem, path):
422-
"""Returns plan in form of dictionary where we take action plan[s] if we reach state s.""" # noqa
421+
"""Returns plan in form of dictionary where we take action plan[s] if we reach state s."""
423422
plan = {}
424423
for s in states:
425424
plan[s] = or_search(s, problem, path)
@@ -461,8 +460,8 @@ def __call__(self, percept):
461460
if len(self.unbacktracked[s1]) == 0:
462461
self.a = None
463462
else:
464-
# else a <- an action b such that result[s', b] = POP(unbacktracked[s']) # noqa
465-
unbacktracked_pop = self.unbacktracked[s1].pop(0) # noqa
463+
# else a <- an action b such that result[s', b] = POP(unbacktracked[s'])
464+
unbacktracked_pop = self.unbacktracked[s1].pop(0)
466465
for (s, b) in self.result.keys():
467466
if self.result[(s, b)] == unbacktracked_pop:
468467
self.a = b
@@ -546,7 +545,7 @@ def __call__(self, s1): # as of now s1 is a state rather than a percept
546545

547546
# an action b in problem.actions(s1) that minimizes costs
548547
self.a = argmin(self.problem.actions(s1),
549-
key=lambda b:self.LRTA_cost(s1, b, self.problem.output(s1, b), self.H))
548+
key=lambda b: self.LRTA_cost(s1, b, self.problem.output(s1, b), self.H))
550549

551550
self.s = s1
552551
return self.a
@@ -573,17 +572,17 @@ def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20):
573572
"""Call genetic_algorithm on the appropriate parts of a problem.
574573
This requires the problem to have states that can mate and mutate,
575574
plus a value method that scores states."""
576-
575+
577576
# NOTE: This is not tested and might not work.
578577
# TODO: Use this function to make Problems work with genetic_algorithm.
579-
578+
580579
s = problem.initial_state
581580
states = [problem.result(s, a) for a in problem.actions(s)]
582581
random.shuffle(states)
583582
return genetic_algorithm(states[:n], problem.value, ngen, pmut)
584583

585584

586-
def genetic_algorithm(population, fitness_fn, gene_pool=['0', '1'], f_thres=None, ngen=1000, pmut=0.1):
585+
def genetic_algorithm(population, fitness_fn, gene_pool=['0', '1'], f_thres=None, ngen=1000, pmut=0.1): # noqa
587586
"""[Figure 4.8]"""
588587
for i in range(ngen):
589588
new_population = []
@@ -954,7 +953,7 @@ def print_boggle(board):
954953
print()
955954

956955

957-
def boggle_neighbors(n2, cache={}): # noqa
956+
def boggle_neighbors(n2, cache={}):
958957
"""Return a list of lists, where the i-th element is the list of indexes
959958
for the neighbors of square i."""
960959
if cache.get(n2):

‎tests/test_csp.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import pytest
2-
from csp import * # noqa
2+
from csp import *
33

44

55
def test_csp_assign():

‎tests/test_games.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import pytest
77

8-
from games import * # noqa
8+
from games import *
99

1010
# Creating the game instances
1111
f52 = Fig52Game()

‎tests/test_grid.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import pytest
2-
from grid import * # noqa
2+
from grid import *
33

44

55
def compare_list(x, y):

‎tests/test_logic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import pytest
2-
from logic import * # noqa
2+
from logic import *
33
from utils import expr_handle_infix_ops, count, Symbol
44

55

‎tests/test_mdp.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from mdp import * # noqa
1+
from mdp import *
22

33

44
def test_value_iteration():

‎tests/test_planning.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from planning import * # noqa
1+
from planning import *
22
from utils import expr
33
from logic import FolKB
44

‎tests/test_probability.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import random
2-
from probability import * # noqa
2+
from probability import *
33
from utils import rounder
44

55

@@ -183,7 +183,7 @@ def test_particle_filtering():
183183
>>> P['rain'] #doctest:+ELLIPSIS
184184
0.2...
185185
186-
# A Joint Probability Distribution is dealt with like this [Figure 13.3]: # noqa
186+
# A Joint Probability Distribution is dealt with like this [Figure 13.3]:
187187
>>> P = JointProbDist(['Toothache', 'Cavity', 'Catch'])
188188
>>> T, F = True, False
189189
>>> P[T, T, T] = 0.108; P[T, T, F] = 0.012; P[F, T, T] = 0.072; P[F, T, F] = 0.008

‎tests/test_search.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import pytest
2-
from search import * # noqa
2+
from search import *
33

44

55
romania_problem = GraphProblem('Arad', 'Bucharest', romania_map)

‎tests/test_text.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import os
33
import random
44

5-
from text import * # noqa
5+
from text import *
66
from utils import isclose, DataFile
77

88

@@ -304,7 +304,7 @@ def test_bigrams():
304304
305305
>>> P3.samples(20)
306306
'flatland by edwin a abbott 1884 to the wake of a certificate from nature herself proving the equal sided triangle'
307-
""" # noqa
307+
"""
308308

309309
if __name__ == '__main__':
310310
pytest.main()

‎tests/test_utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import pytest
2-
from utils import * # noqa
2+
from utils import *
33
import random
44

55
def test_removeall_list():

‎text.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ def samples(self, n):
2626
return ' '.join(self.sample() for i in range(n))
2727

2828

29-
3029
class NgramTextModel(CountingProbDist):
3130

3231
"""This is a discrete probability distribution over n-tuples of words.
@@ -80,7 +79,7 @@ def samples(self, nwords):
8079

8180
class NgramCharModel(NgramTextModel):
8281
def add_empty(self, words, n):
83-
return ' ' * (n - 1) + words
82+
return ' ' * (n - 1) + words
8483

8584
def add_sequence(self, words):
8685
for word in words:
@@ -362,14 +361,13 @@ def decode(self, ciphertext):
362361
solution.state[' '] = ' '
363362
return translate(self.ciphertext, lambda c: solution.state[c])
364363

365-
366364
def score(self, code):
367365
"""Score is product of word scores, unigram scores, and bigram scores.
368366
This can get very small, so we use logs and exp."""
369367

370368
# remake code dictionary to contain translation for all characters
371369
full_code = code.copy()
372-
full_code.update({x:x for x in self.chardomain if x not in code})
370+
full_code.update({x: x for x in self.chardomain if x not in code})
373371
full_code[' '] = ' '
374372
text = translate(self.ciphertext, lambda c: full_code[c])
375373

‎utils.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import os.path
88
import random
99
import math
10+
import functools
1011

1112
# ______________________________________________________________________________
1213
# Functions on Sequences and Iterables
@@ -258,6 +259,7 @@ def step(x):
258259
"""Return activation value of x with sign function"""
259260
return 1 if x >= 0 else 0
260261

262+
261263
def gaussian(mean, st_dev, x):
262264
"""Given the mean and standard deviation of a distribution, it returns the probability of x."""
263265
return 1/(math.sqrt(2*math.pi)*st_dev)*math.e**(-0.5*(float(x-mean)/st_dev)**2)
@@ -656,7 +658,7 @@ def extend(self, items):
656658
def pop(self):
657659
if len(self.queue) > 0:
658660
return self.queue.popleft()
659-
else :
661+
else:
660662
raise Exception('FIFOQueue is empty')
661663

662664
def __len__(self):

0 commit comments

Comments
 (0)
Please sign in to comment.