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

Skip to content

Commit 194a2f1

Browse files
committed
Style: address pep8 warnings.
1 parent 08b6aea commit 194a2f1

File tree

11 files changed

+66
-71
lines changed

11 files changed

+66
-71
lines changed

csp.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,9 @@ def result(self, state, action):
106106
def goal_test(self, state):
107107
"The goal is to assign all variables, with all constraints satisfied."
108108
assignment = dict(state)
109-
return (len(assignment) == len(self.variables) and
110-
all(self.nconflicts(variables, assignment[variables], assignment) == 0 for variables in self.variables))
109+
return (len(assignment) == len(self.variables)
110+
and all(self.nconflicts(variables, assignment[variables], assignment) == 0
111+
for variables in self.variables))
111112

112113
# These are for constraint propagation
113114

@@ -663,4 +664,3 @@ def solve_zebra(algorithm=min_conflicts, **args):
663664
print(var, end=' ')
664665
print()
665666
return ans['Zebra'], ans['Water'], z.nassigns, ans
666-

games.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def terminal_test(self, state):
232232
return state not in ('A', 'B', 'C', 'D')
233233

234234
def to_move(self, state):
235-
return 'MIN' if state in 'BCD' else 'MAX'
235+
return 'MIN' if state in 'BCD' else 'MAX'
236236

237237

238238
class TicTacToe(Game):
@@ -266,7 +266,7 @@ def result(self, state, move):
266266

267267
def utility(self, state, player):
268268
"Return the value to player; 1 for win, -1 for loss, 0 otherwise."
269-
return state.utility if player == 'X' else -state.utility
269+
return state.utility if player == 'X' else -state.utility
270270

271271
def terminal_test(self, state):
272272
"A state is terminal if it is won or there are no empty squares."
@@ -343,7 +343,7 @@ def mouse_click(self, x, y):
343343
if player == 'human':
344344
x, y = int(3*x/self.width) + 1, int(3*y/self.height) + 1
345345
if (x, y) not in self.ttt.actions(self.state):
346-
#Invalid move
346+
# Invalid move
347347
return
348348
move = (x, y)
349349
elif player == 'alphabeta':
@@ -368,14 +368,14 @@ def draw_board(self):
368368
self.draw_x(mark)
369369
elif board[mark] == 'O':
370370
self.draw_o(mark)
371-
#End game message
372371
if self.ttt.terminal_test(self.state):
372+
# End game message
373373
utility = self.ttt.utility(self.state, self.ttt.to_move(self.ttt.initial))
374374
if utility == 0:
375375
self.text_n('Game Draw!', 0.1, 0.1)
376376
else:
377377
self.text_n('Player {} wins!'.format(1 if utility>0 else 2), 0.1, 0.1)
378-
else: #print which player's turn it is
378+
else: # Print which player's turn it is
379379
self.text_n("Player {}'s move({})".format(self.turn+1, self.players[self.turn]), 0.1, 0.1)
380380

381381
self.update()

ipyviews.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ def handle_click(self, coordinates):
133133
def map_to_render(self):
134134
default_representation = {"val": "default", "tooltip": ""}
135135
world_map = [[copy.deepcopy(default_representation) for _ in range(self.world.width)]
136-
for _ in range(self.world.height)]
136+
for _ in range(self.world.height)]
137137

138138
for thing in self.world.things:
139139
row, column = thing.location
@@ -150,6 +150,7 @@ def map_to_render(self):
150150

151151
def show(self):
152152
clear_output()
153-
total_html = _GRID_WORLD_HTML.format(self.object_name(), self.map_to_render(),
153+
total_html = _GRID_WORLD_HTML.format(
154+
self.object_name(), self.map_to_render(),
154155
self.block_size, json.dumps(self.representation), _JS_GRID_WORLD)
155156
display(HTML(total_html))

learning.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,6 @@ def __init__(self, attr, attrname=None, branches=None):
290290
self.attrname = attrname or attr
291291
self.branches = branches or {}
292292

293-
294293
def __call__(self, example):
295294
"Given an example, classify it using the attribute and the branches."
296295
attrvalue = example[self.attr]

logic.py

Lines changed: 28 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ def pl_true(exp, model={}):
238238
and False if it is false. If the model does not specify the value for
239239
every proposition, this may return None to indicate 'not obvious';
240240
this may happen even when the expression is tautological."""
241-
if exp == True or exp == False:
241+
if exp in (True, False):
242242
return exp
243243
op, args = exp.op, exp.args
244244
if is_prop_symbol(op):
@@ -639,7 +639,7 @@ def inspect_literal(literal):
639639
def WalkSAT(clauses, p=0.5, max_flips=10000):
640640
"""Checks for satisfiability of all clauses by randomly flipping values of variables
641641
"""
642-
# set of all symbols in all clauses
642+
# Set of all symbols in all clauses
643643
symbols = set(sym for clause in clauses for sym in prop_symbols(clause))
644644
# model is a random assignment of true/false to the symbols in clauses
645645
model = {s: random.choice([True, False]) for s in symbols}
@@ -655,14 +655,14 @@ def WalkSAT(clauses, p=0.5, max_flips=10000):
655655
else:
656656
# Flip the symbol in clause that maximizes number of sat. clauses
657657
def sat_count(sym):
658-
#returns the the number of clauses satisfied after flipping the symbol
658+
# Return the the number of clauses satisfied after flipping the symbol.
659659
model[sym] = not model[sym]
660660
count = len([clause for clause in clauses if pl_true(clause, model)])
661661
model[sym] = not model[sym]
662662
return count
663663
sym = argmax(prop_symbols(clause), key=sat_count)
664664
model[sym] = not model[sym]
665-
#If no solution is found within the flip limit, we return failure
665+
# If no solution is found within the flip limit, we return failure
666666
return None
667667

668668
# ______________________________________________________________________________
@@ -686,71 +686,71 @@ def SAT_plan(init, transition, goal, t_max, SAT_solver=dpll_satisfiable):
686686
"""Converts a planning problem to Satisfaction problem by translating it to a cnf sentence.
687687
[Figure 7.22]"""
688688

689-
#Functions used by SAT_plan
689+
# Functions used by SAT_plan
690690
def translate_to_SAT(init, transition, goal, time):
691691
clauses = []
692692
states = [state for state in transition]
693693

694-
#Symbol claiming state s at time t
694+
# Symbol claiming state s at time t
695695
state_counter = itertools.count()
696696
for s in states:
697697
for t in range(time+1):
698-
state_sym[(s, t)] = Expr("State_{}".format(next(state_counter)))
698+
state_sym[s, t] = Expr("State_{}".format(next(state_counter)))
699699

700-
#Add initial state axiom
700+
# Add initial state axiom
701701
clauses.append(state_sym[init, 0])
702702

703-
#Add goal state axiom
703+
# Add goal state axiom
704704
clauses.append(state_sym[goal, time])
705705

706-
#All possible transitions
706+
# All possible transitions
707707
transition_counter = itertools.count()
708708
for s in states:
709709
for action in transition[s]:
710710
s_ = transition[s][action]
711711
for t in range(time):
712-
#Action 'action' taken from state 's' at time 't' to reach 's_'
713-
action_sym[(s, action, t)] = Expr("Transition_{}".format(next(transition_counter)))
712+
# Action 'action' taken from state 's' at time 't' to reach 's_'
713+
action_sym[s, action, t] = Expr("Transition_{}".format(next(transition_counter)))
714714

715715
# Change the state from s to s_
716716
clauses.append(action_sym[s, action, t] |'==>'| state_sym[s, t])
717717
clauses.append(action_sym[s, action, t] |'==>'| state_sym[s_, t + 1])
718718

719-
#Allow only one state at any time
719+
# Allow only one state at any time
720720
for t in range(time+1):
721-
#must be a state at any time
722-
clauses.append(associate('|', [ state_sym[s, t] for s in states ]))
721+
# must be a state at any time
722+
clauses.append(associate('|', [state_sym[s, t] for s in states]))
723723

724724
for s in states:
725725
for s_ in states[states.index(s)+1:]:
726-
#for each pair of states s, s_ only one is possible at time t
726+
# for each pair of states s, s_ only one is possible at time t
727727
clauses.append((~state_sym[s, t]) | (~state_sym[s_, t]))
728728

729-
#Restrict to one transition per timestep
729+
# Restrict to one transition per timestep
730730
for t in range(time):
731-
#list of possible transitions at time t
731+
# list of possible transitions at time t
732732
transitions_t = [tr for tr in action_sym if tr[2] == t]
733733

734-
#make sure atleast one of the transition happens
735-
clauses.append(associate('|', [ action_sym[tr] for tr in transitions_t ]))
734+
# make sure at least one of the transitions happens
735+
clauses.append(associate('|', [action_sym[tr] for tr in transitions_t]))
736736

737737
for tr in transitions_t:
738738
for tr_ in transitions_t[transitions_t.index(tr) + 1 :]:
739-
#there cannot be two transitions tr and tr_ at time t
740-
clauses.append((~action_sym[tr]) | (~action_sym[tr_]))
739+
# there cannot be two transitions tr and tr_ at time t
740+
clauses.append(~action_sym[tr] | ~action_sym[tr_])
741741

742-
#Combine the clauses to form the cnf
742+
# Combine the clauses to form the cnf
743743
return associate('&', clauses)
744744

745745
def extract_solution(model):
746-
true_transitions = [ t for t in action_sym if model[action_sym[t]]]
747-
#Sort transitions based on time which is the 3rd element of the tuple
746+
true_transitions = [t for t in action_sym if model[action_sym[t]]]
747+
# Sort transitions based on time, which is the 3rd element of the tuple
748748
true_transitions.sort(key = lambda x: x[2])
749-
return [ action for s, action, time in true_transitions ]
749+
return [action for s, action, time in true_transitions]
750750

751-
#Body of SAT_plan algorithm
751+
# Body of SAT_plan algorithm
752752
for t in range(t_max):
753-
#dcitionaries to help extract the solution from model
753+
# dictionaries to help extract the solution from model
754754
state_sym = {}
755755
action_sym = {}
756756

@@ -1062,5 +1062,3 @@ def simp(x):
10621062
def d(y, x):
10631063
"Differentiate and then simplify."
10641064
return simp(diff(y, x))
1065-
1066-

mdp.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,9 @@ def to_arrows(self, policy):
102102
"""
103103

104104
sequential_decision_environment = GridMDP([[-0.04, -0.04, -0.04, +1],
105-
[-0.04, None, -0.04, -1],
106-
[-0.04, -0.04, -0.04, -0.04]],
107-
terminals=[(3, 2), (3, 1)])
105+
[-0.04, None, -0.04, -1],
106+
[-0.04, -0.04, -0.04, -0.04]],
107+
terminals=[(3, 2), (3, 1)])
108108

109109
# ______________________________________________________________________________
110110

nlp.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,3 @@ def extender(self, edge):
182182
for (i, j, A, alpha, B1b) in self.chart[j]:
183183
if B1b and B == B1b[0]:
184184
self.add_edge([i, k, A, alpha + [edge], B1b[1:]])
185-
186-
187-

probability.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -526,7 +526,7 @@ class HiddenMarkovModel:
526526

527527
""" A Hidden markov model which takes Transition model and Sensor model as inputs"""
528528

529-
def __init__(self, transition_model, sensor_model, prior= [0.5, 0.5]):
529+
def __init__(self, transition_model, sensor_model, prior=[0.5, 0.5]):
530530
self.transition_model = transition_model
531531
self.sensor_model = sensor_model
532532
self.prior = prior
@@ -598,7 +598,7 @@ def fixed_lag_smoothing(e_t, HMM, d, ev, t):
598598
O_t = vector_to_diagonal(HMM.sensor_dist(e_t))
599599
if t > d:
600600
f = forward(HMM, f, e_t)
601-
O_tmd = vector_to_diagonal(HMM.sensor_dist(ev[t- d]))
601+
O_tmd = vector_to_diagonal(HMM.sensor_dist(ev[t - d]))
602602
B = matrix_multiplication(inverse_matrix(O_tmd), inverse_matrix(T_model), B, T_model, O_t)
603603
else:
604604
B = matrix_multiplication(B, T_model, O_t)

rl.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def __call__(self, percept):
5454
return self.a
5555

5656
def update_state(self, percept):
57-
''' To be overriden in most cases. The default case
57+
''' To be overridden in most cases. The default case
5858
assumes th percept to be of type (state, reward)'''
5959
return percept
6060

@@ -104,19 +104,20 @@ def __call__(self, percept):
104104
Q, Nsa, s, a, r = self.Q, self.Nsa, self.s, self.a, self.r
105105
alpha, gamma, terminals, actions_in_state = self.alpha, self.gamma, self.terminals, self.actions_in_state
106106
if s1 in terminals:
107-
Q[(s1, None)] = r1
107+
Q[s1, None] = r1
108108
if s is not None:
109-
Nsa[(s, a)] += 1
110-
Q[(s, a)] += alpha(Nsa[(s, a)])*(r+gamma*max([Q[(s1, a1)] for a1 in actions_in_state(s1)])-Q[(s, a)])
109+
Nsa[s, a] += 1
110+
Q[s, a] += alpha(Nsa[s, a]) * (r + gamma * max(Q[s1, a1] for a1 in actions_in_state(s1))
111+
- Q[s, a])
111112
if s1 in terminals:
112113
self.s = self.a = self.r = None
113114
else:
114115
self.s, self.r = s1, r1
115-
self.a = argmax(actions_in_state(s1), key=lambda a1: self.f(Q[(s1, a1)], Nsa[(s1, a1)]))
116+
self.a = argmax(actions_in_state(s1), key=lambda a1: self.f(Q[s1, a1], Nsa[s1, a1]))
116117
return self.a
117118

118119
def update_state(self, percept):
119-
''' To be overriden in most cases. The default case
120+
''' To be overridden in most cases. The default case
120121
assumes the percept to be of type (state, reward)'''
121122
return percept
122123

search.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,9 @@ def result(self, state, action):
5151

5252
def goal_test(self, state):
5353
"""Return True if the state is a goal. The default method compares the
54-
state to self.goal or checks for state in self.goal if it is a list, as specified in the constructor. Override this
55-
method if checking against a single self.goal is not enough."""
54+
state to self.goal or checks for state in self.goal if it is a
55+
list, as specified in the constructor. Override this method if
56+
checking against a single self.goal is not enough."""
5657
if isinstance(self.goal, list):
5758
return is_in(state, self.goal)
5859
else:
@@ -411,7 +412,7 @@ def or_search(state, problem, path):
411412

412413
def and_search(states, problem, path):
413414
"returns plan in form of dictionary where we take action plan[s] if we reach state s" # noqa
414-
plan = dict()
415+
plan = {}
415416
for s in states:
416417
plan[s] = or_search(s, problem, path)
417418
if plan[s] is None:
@@ -464,7 +465,7 @@ def __call__(self, percept):
464465
return self.a
465466

466467
def update_state(self, percept):
467-
'''To be overriden in most cases. The default case
468+
'''To be overridden in most cases. The default case
468469
assumes the percept to be of type state.'''
469470
return percept
470471

@@ -535,12 +536,12 @@ def __call__(self, s1): # as of now s1 is a state rather than a percept
535536
# self.result[(self.s, self.a)] = s1 # no need as we are using problem.output
536537

537538
# minimum cost for action b in problem.actions(s)
538-
self.H[self.s] = min([self.LRTA_cost(self.s, b, self.problem.output(self.s, b), self.H)
539-
for b in self.problem.actions(self.s)])
539+
self.H[self.s] = min(self.LRTA_cost(self.s, b, self.problem.output(self.s, b), self.H)
540+
for b in self.problem.actions(self.s))
540541

541542
# costs for action b in problem.actions(s1)
542543
costs = [self.LRTA_cost(s1, b, self.problem.output(s1, b), self.H)
543-
for b in self.problem.actions(s1)]
544+
for b in self.problem.actions(s1)]
544545
# an action b in problem.actions(s1) that minimizes costs
545546
self.a = list(self.problem.actions(s1))[costs.index(min(costs))]
546547

@@ -780,8 +781,8 @@ def distance_to_node(n):
780781
NT=dict(WA=1, Q=1),
781782
NSW=dict(Q=1, V=1)))
782783
australia_map.locations = dict(WA=(120, 24), NT=(135, 20), SA=(135, 30),
783-
Q=(145, 20), NSW=(145, 32), T=(145, 42),
784-
V=(145, 37))
784+
Q=(145, 20), NSW=(145, 32), T=(145, 42),
785+
V=(145, 37))
785786

786787

787788
class GraphProblem(Problem):
@@ -813,8 +814,10 @@ def h(self, node):
813814

814815
class GraphProblemStochastic(GraphProblem):
815816
"""
816-
A version of Graph Problem where an action can lead to undeterministic output i.e. multiple possible states
817-
Define the graph as dict(A = dict(Action = [[<Result 1>, <Result 2>, ...],<cost>], ...), ...)
817+
A version of GraphProblem where an action can lead to
818+
nondeterministic output i.e. multiple possible states
819+
820+
Define the graph as dict(A = dict(Action = [[<Result 1>, <Result 2>, ...], <cost>], ...), ...)
818821
A the dictionary format is different, make sure the graph is created as a directed graph
819822
"""
820823

@@ -1153,7 +1156,3 @@ def compare_graph_searchers():
11531156
GraphProblem('Q', 'WA', australia_map)],
11541157
header=['Searcher', 'romania_map(Arad, Bucharest)',
11551158
'romania_map(Oradea, Neamt)', 'australia_map'])
1156-
1157-
# ______________________________________________________________________________
1158-
1159-

utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def weighted_sampler(seq, weights):
191191

192192
return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]
193193

194-
def rounder(numbers, d = 4):
194+
def rounder(numbers, d=4):
195195
"Round a single number, or sequence of numbers, to d decimal places."
196196
if isinstance(numbers, (int, float)):
197197
return round(numbers, d)

0 commit comments

Comments
 (0)