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

Skip to content

Commit 0dbb1f6

Browse files
Style: address pep8 warnings in main code.
1 parent 2c458ae commit 0dbb1f6

File tree

12 files changed

+150
-121
lines changed

12 files changed

+150
-121
lines changed

agents.py

Lines changed: 40 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ def __add__(self, heading):
362362
}.get(heading, None)
363363

364364
def move_forward(self, from_location):
365-
x,y = from_location
365+
x, y = from_location
366366
if self.direction == self.R:
367367
return (x+1, y)
368368
elif self.direction == self.L:
@@ -389,11 +389,12 @@ def __init__(self, width=10, height=10):
389389
self.width = width
390390
self.height = height
391391
self.observers = []
392-
#Sets iteration start and end (no walls).
393-
self.x_start,self.y_start = (0,0)
394-
self.x_end,self.y_end = (self.width, self.height)
392+
# Sets iteration start and end (no walls).
393+
self.x_start, self.y_start = (0, 0)
394+
self.x_end, self.y_end = (self.width, self.height)
395395

396396
perceptible_distance = 1
397+
397398
def things_near(self, location, radius=None):
398399
"Return all things within radius of location."
399400
if radius is None:
@@ -447,7 +448,7 @@ def move_to(self, thing, destination):
447448
# for obs in self.observers:
448449
# obs.thing_added(thing)
449450

450-
def add_thing(self, thing, location=(1, 1), exclude_duplicate_class_items = False):
451+
def add_thing(self, thing, location=(1, 1), exclude_duplicate_class_items=False):
451452
'''Adds things to the world.
452453
If (exclude_duplicate_class_items) then the item won't be added if the location
453454
has at least one item of the same class'''
@@ -462,7 +463,7 @@ def is_inbounds(self, location):
462463
x,y = location
463464
return not (x < self.x_start or x >= self.x_end or y < self.y_start or y >= self.y_end)
464465

465-
def random_location_inbounds(self, exclude = None):
466+
def random_location_inbounds(self, exclude=None):
466467
'''Returns a random location that is inbounds (within walls if we have walls)'''
467468
location = (random.randint(self.x_start, self.x_end), random.randint(self.y_start, self.y_end))
468469
if exclude is not None:
@@ -486,14 +487,14 @@ def add_walls(self):
486487
'''Put walls around the entire perimeter of the grid.'''
487488
for x in range(self.width):
488489
self.add_thing(Wall(), (x, 0))
489-
self.add_thing(Wall(), (x, self.height-1))
490+
self.add_thing(Wall(), (x, self.height - 1))
490491
for y in range(self.height):
491492
self.add_thing(Wall(), (0, y))
492-
self.add_thing(Wall(), (self.width-1, y))
493+
self.add_thing(Wall(), (self.width - 1, y))
493494

494-
#Updates iteration start and end (with walls).
495-
self.x_start,self.y_start = (1,1)
496-
self.x_end,self.y_end = (self.width-1, self.height-1)
495+
# Updates iteration start and end (with walls).
496+
self.x_start, self.y_start = (1, 1)
497+
self.x_end, self.y_end = (self.width - 1, self.height - 1)
497498

498499
def add_observer(self, observer):
499500
"""Adds an observer to the list of observers.
@@ -662,6 +663,7 @@ class Wumpus(Agent):
662663
class Stench(Thing):
663664
pass
664665

666+
665667
class Explorer(Agent):
666668
holding = []
667669
has_arrow = True
@@ -674,8 +676,9 @@ def can_grab(self, thing):
674676

675677

676678
class WumpusEnvironment(XYEnvironment):
677-
pit_probability = 0.2 #Probability to spawn a pit in a location. (From Chapter 7.2)
678-
#Room should be 4x4 grid of rooms. The extra 2 for walls
679+
pit_probability = 0.2 # Probability to spawn a pit in a location. (From Chapter 7.2)
680+
# Room should be 4x4 grid of rooms. The extra 2 for walls
681+
679682
def __init__(self, agent_program, width=6, height=6):
680683
super(WumpusEnvironment, self).__init__(width, height)
681684
self.init_world(agent_program)
@@ -690,47 +693,46 @@ def init_world(self, program):
690693
for x in range(self.x_start, self.x_end):
691694
for y in range(self.y_start, self.y_end):
692695
if random.random() < self.pit_probability:
693-
self.add_thing(Pit(), (x,y), True)
694-
self.add_thing(Breeze(), (x - 1,y), True)
695-
self.add_thing(Breeze(), (x,y - 1), True)
696-
self.add_thing(Breeze(), (x + 1,y), True)
697-
self.add_thing(Breeze(), (x,y + 1), True)
696+
self.add_thing(Pit(), (x, y), True)
697+
self.add_thing(Breeze(), (x - 1, y), True)
698+
self.add_thing(Breeze(), (x, y - 1), True)
699+
self.add_thing(Breeze(), (x + 1, y), True)
700+
self.add_thing(Breeze(), (x, y + 1), True)
698701

699702
"WUMPUS"
700-
w_x, w_y = self.random_location_inbounds(exclude = (1,1))
703+
w_x, w_y = self.random_location_inbounds(exclude=(1, 1))
701704
self.add_thing(Wumpus(lambda x: ""), (w_x, w_y), True)
702705
self.add_thing(Stench(), (w_x - 1, w_y), True)
703706
self.add_thing(Stench(), (w_x + 1, w_y), True)
704707
self.add_thing(Stench(), (w_x, w_y - 1), True)
705708
self.add_thing(Stench(), (w_x, w_y + 1), True)
706709

707710
"GOLD"
708-
self.add_thing(Gold(), self.random_location_inbounds(exclude = (1,1)), True)
711+
self.add_thing(Gold(), self.random_location_inbounds(exclude=(1, 1)), True)
709712
#self.add_thing(Gold(), (2,1), True) Making debugging a whole lot easier
710713

711714
"AGENT"
712-
self.add_thing(Explorer(program), (1,1), True)
715+
self.add_thing(Explorer(program), (1, 1), True)
713716

714-
def get_world(self, show_walls = True):
717+
def get_world(self, show_walls=True):
715718
'''returns the items in the world'''
716719
result = []
717-
x_start,y_start = (0,0) if show_walls else (1,1)
718-
x_end,y_end = (self.width, self.height) if show_walls else (self.width - 1, self.height - 1)
720+
x_start, y_start = (0, 0) if show_walls else (1, 1)
721+
x_end, y_end = (self.width, self.height) if show_walls else (self.width - 1, self.height - 1)
719722
for x in range(x_start, x_end):
720723
row = []
721724
for y in range(y_start, y_end):
722-
row.append(self.list_things_at((x,y)))
725+
row.append(self.list_things_at((x, y)))
723726
result.append(row)
724727
return result
725728

726-
def percepts_from(self, agent, location, tclass = Thing):
729+
def percepts_from(self, agent, location, tclass=Thing):
727730
'''Returns percepts from a given location, and replaces some items with percepts from chapter 7.'''
728731
thing_percepts = {
729732
Gold: Glitter(),
730733
Wall: Bump(),
731734
Wumpus: Stench(),
732-
Pit: Breeze()
733-
}
735+
Pit: Breeze()}
734736
'''Agents don't need to get their percepts'''
735737
thing_percepts[agent.__class__] = None
736738

@@ -740,19 +742,19 @@ def percepts_from(self, agent, location, tclass = Thing):
740742

741743

742744
result = [thing_percepts.get(thing.__class__, thing) for thing in self.things
743-
if thing.location == location and isinstance(thing, tclass)]
745+
if thing.location == location and isinstance(thing, tclass)]
744746
return result if len(result) else [None]
745747

746748
def percept(self, agent):
747749
'''Returns things in adjacent (not diagonal) cells of the agent.
748750
Result format: [Left, Right, Up, Down, Center / Current location]'''
749-
x,y = agent.location
751+
x, y = agent.location
750752
result = []
751-
result.append(self.percepts_from(agent, (x - 1,y)))
752-
result.append(self.percepts_from(agent, (x + 1,y)))
753-
result.append(self.percepts_from(agent, (x,y - 1)))
754-
result.append(self.percepts_from(agent, (x,y + 1)))
755-
result.append(self.percepts_from(agent, (x,y)))
753+
result.append(self.percepts_from(agent, (x - 1, y)))
754+
result.append(self.percepts_from(agent, (x + 1, y)))
755+
result.append(self.percepts_from(agent, (x, y - 1)))
756+
result.append(self.percepts_from(agent, (x, y + 1)))
757+
result.append(self.percepts_from(agent, (x, y)))
756758

757759
'''The wumpus gives out a a loud scream once it's killed.'''
758760
wumpus = [thing for thing in self.things if isinstance(thing, Wumpus)]
@@ -781,14 +783,14 @@ def execute_action(self, agent, action):
781783
agent.performance -= 1
782784
elif action == 'Grab':
783785
things = [thing for thing in self.list_things_at(agent.location)
784-
if agent.can_grab(thing)]
786+
if agent.can_grab(thing)]
785787
if len(things):
786788
print("Grabbing", things[0].__class__.__name__)
787789
if len(things):
788790
agent.holding.append(things[0])
789791
agent.performance -= 1
790792
elif action == 'Climb':
791-
if agent.location == (1,1): #Agent can only climb out of (1,1)
793+
if agent.location == (1, 1): # Agent can only climb out of (1,1)
792794
agent.performance += 1000 if Gold() in agent.holding else 0
793795
self.delete_thing(agent)
794796
elif action == 'Shoot':
@@ -831,6 +833,7 @@ def is_done(self):
831833
#Almost done. Arrow needs to be implemented
832834
# ______________________________________________________________________________
833835

836+
834837
def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
835838
"""See how well each of several agents do in n instances of an environment.
836839
Pass in a factory (constructor) for environments, and several for agents.

canvas.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def mouse_move(self, x, y):
3636
def execute(self, exec_str):
3737
"Stores the command to be exectued to a list which is used later during update()"
3838
if not isinstance(exec_str, str):
39-
print("Invalid execution argument:",exec_str)
39+
print("Invalid execution argument:", exec_str)
4040
self.alert("Recieved invalid execution command format")
4141
prefix = "{0}_canvas_object.".format(self.id)
4242
self.exec_list.append(prefix + exec_str + ';')
@@ -98,14 +98,14 @@ def font(self, font):
9898
"Changes the font of text"
9999
self.execute('font("{0}")'.format(font))
100100

101-
def text(self, txt, x, y, fill = True):
101+
def text(self, txt, x, y, fill=True):
102102
"Display a text at (x, y)"
103103
if fill:
104104
self.execute('fill_text("{0}", {1}, {2})'.format(txt, x, y))
105105
else:
106106
self.execute('stroke_text("{0}", {1}, {2})'.format(txt, x, y))
107107

108-
def text_n(self, txt, xn, yn, fill = True):
108+
def text_n(self, txt, xn, yn, fill=True):
109109
"Similar to text(), but with normalized coordinates"
110110
x = round(xn * self.width)
111111
y = round(yn * self.height)
@@ -117,6 +117,6 @@ def alert(self, message):
117117

118118
def update(self):
119119
"Execute the JS code to execute the commands queued by execute()"
120-
exec_code = "<script>\n"+'\n'.join(self.exec_list)+"\n</script>"
120+
exec_code = "<script>\n" + '\n'.join(self.exec_list) + "\n</script>"
121121
self.exec_list = []
122122
display(HTML(exec_code))

csp.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ def display(self, assignment):
481481
for var in range(n):
482482
if assignment.get(var, '') == val:
483483
ch = 'Q'
484-
elif (var+val) % 2 == 0:
484+
elif (var + val) % 2 == 0:
485485
ch = '.'
486486
else:
487487
ch = '-'
@@ -492,7 +492,7 @@ def display(self, assignment):
492492
ch = '*'
493493
else:
494494
ch = ' '
495-
print(str(self.nconflicts(var, val, assignment))+ch, end=' ')
495+
print(str(self.nconflicts(var, val, assignment)) + ch, end=' ')
496496
print()
497497

498498
# ______________________________________________________________________________

games.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def max_value(state, alpha, beta, depth):
9696
v = -infinity
9797
for a in game.actions(state):
9898
v = max(v, min_value(game.result(state, a),
99-
alpha, beta, depth+1))
99+
alpha, beta, depth + 1))
100100
if v >= beta:
101101
return v
102102
alpha = max(alpha, v)
@@ -108,7 +108,7 @@ def min_value(state, alpha, beta, depth):
108108
v = infinity
109109
for a in game.actions(state):
110110
v = min(v, max_value(game.result(state, a),
111-
alpha, beta, depth+1))
111+
alpha, beta, depth + 1))
112112
if v <= alpha:
113113
return v
114114
beta = min(beta, v)
@@ -245,8 +245,8 @@ def __init__(self, h=3, v=3, k=3):
245245
self.h = h
246246
self.v = v
247247
self.k = k
248-
moves = [(x, y) for x in range(1, h+1)
249-
for y in range(1, v+1)]
248+
moves = [(x, y) for x in range(1, h + 1)
249+
for y in range(1, v + 1)]
250250
self.initial = GameState(to_move='X', utility=0, board={}, moves=moves)
251251

252252
def actions(self, state):
@@ -274,8 +274,8 @@ def terminal_test(self, state):
274274

275275
def display(self, state):
276276
board = state.board
277-
for x in range(1, self.h+1):
278-
for y in range(1, self.v+1):
277+
for x in range(1, self.h + 1):
278+
for y in range(1, self.v + 1):
279279
print(board.get((x, y), '.'), end=' ')
280280
print()
281281

@@ -315,7 +315,7 @@ def __init__(self, h=7, v=6, k=4):
315315

316316
def actions(self, state):
317317
return [(x, y) for (x, y) in state.moves
318-
if y == 1 or (x, y-1) in state.board]
318+
if y == 1 or (x, y - 1) in state.board]
319319

320320

321321
class Canvas_TicTacToe(Canvas):
@@ -374,7 +374,7 @@ def draw_board(self):
374374
if utility == 0:
375375
self.text_n('Game Draw!', 0.1, 0.1)
376376
else:
377-
self.text_n('Player {} wins!'.format(1 if utility>0 else 2), 0.1, 0.1)
377+
self.text_n('Player {} wins!'.format(1 if utility > 0 else 2), 0.1, 0.1)
378378
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

learning.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -555,7 +555,7 @@ def BackPropagationLearner(dataset, net, learning_rate, epoches):
555555
o_units = len(o_nodes)
556556
err = [t_val[i] - o_nodes[i].value
557557
for i in range(o_units)]
558-
delta[-1] = [(o_nodes[i].value)*(1 - o_nodes[i].value) *
558+
delta[-1] = [(o_nodes[i].value) * (1 - o_nodes[i].value) *
559559
(err[i]) for i in range(o_units)]
560560

561561
# Backward pass
@@ -620,7 +620,7 @@ def predict(example):
620620
def Linearlearner(dataset, learning_rate=0.01, epochs=100):
621621
"""Define with learner = Linearlearner(data); infer with learner(x)."""
622622
idx_i = dataset.inputs
623-
idx_t = dataset.target # As of now, dataset.target gives only one index.
623+
idx_t = dataset.target # As of now, dataset.target gives only one index.
624624
examples = dataset.examples
625625

626626
# X transpose
@@ -794,23 +794,23 @@ def cross_validation(learner, size, dataset, k=10, trials=1):
794794
k=10, trials=1)
795795
trial_errT += errT
796796
trial_errV += errV
797-
return trial_errT/trials, trial_errV/trials
797+
return trial_errT / trials, trial_errV / trials
798798
else:
799799
fold_errT = 0
800800
fold_errV = 0
801801
n = len(dataset.examples)
802802
examples = dataset.examples
803803
for fold in range(k):
804804
random.shuffle(dataset.examples)
805-
train_data, val_data = train_and_test(dataset, fold * (n/k),
806-
(fold + 1) * (n/k))
805+
train_data, val_data = train_and_test(dataset, fold * (n / k),
806+
(fold + 1) * (n / k))
807807
dataset.examples = train_data
808808
h = learner(dataset, size)
809809
fold_errT += test(h, dataset, train_data)
810810
fold_errV += test(h, dataset, val_data)
811811
# Reverting back to original once test is completed
812812
dataset.examples = examples
813-
return fold_errT/k, fold_errV/k
813+
return fold_errT / k, fold_errV / k
814814

815815

816816
def cross_validation_wrapper(learner, dataset, k=10, trials=1):

0 commit comments

Comments
 (0)