FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Use dict comprehensions now that we can. · throbs/aima-python@3c2639a · GitHub

Repository navigation

Commit 3c2639a

Browse files
committed
Use dict comprehensions now that we can.
1 parent 7776583 commit 3c2639a

5 files changed

Lines changed: 33 additions & 33 deletions

File tree

‎csp.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def support_pruning(self):
115115
"""Make sure we can prune values from domains. (We want to pay
116116
for this only if we use it.)"""
117117
if self.curr_domains is None:
118-
self.curr_domains = dict((v, list(self.domains[v])) for v in self.variables)
118+
self.curr_domains = {v: list(self.domains[v]) for v in self.variables}
119119

120120
def suppose(self, var, value):
121121
"Start accumulating inferences from assuming var=value."
@@ -137,8 +137,8 @@ def choices(self, var):
137137
def infer_assignment(self):
138138
"Return the partial assignment implied by the current inferences."
139139
self.support_pruning()
140-
return dict((v, self.curr_domains[v][0])
141-
for v in self.variables if 1 == len(self.curr_domains[v]))
140+
return {v: self.curr_domains[v][0]
141+
for v in self.variables if 1 == len(self.curr_domains[v])}
142142

143143
def restore(self, removals):
144144
"Undo a supposition and all inferences from it."
@@ -512,7 +512,7 @@ def flatten(seqs): return sum(seqs, [])
512512
_ROWS = flatten([list(map(flatten, list(zip(*brow)))) for brow in _BGRID])
513513
_COLS = list(zip(*_ROWS))
514514

515-
_NEIGHBORS = dict([(v, set()) for v in flatten(_ROWS)])
515+
_NEIGHBORS = {v: set() for v in flatten(_ROWS)}
516516
for unit in map(set, _BOXES + _ROWS + _COLS):
517517
for v in unit:
518518
_NEIGHBORS[v].update(unit - set([v]))
@@ -567,8 +567,8 @@ def __init__(self, grid):
567567
the digits 1-9 denote a filled cell, '.' or '0' an empty one;
568568
other characters are ignored."""
569569
squares = iter(re.findall(r'\d|\.', grid))
570-
domains = dict((var, ([ch] if ch in '123456789' else '123456789'))
571-
for var, ch in zip(flatten(self.rows), squares))
570+
domains = {var: [ch] if ch in '123456789' else '123456789'
571+
for var, ch in zip(flatten(self.rows), squares)}
572572
for _ in squares:
573573
raise ValueError("Not a Sudoku grid", grid) # Too many squares
574574
CSP.__init__(self, None, domains, self.neighbors, different_values_constraint)

‎learning.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -241,9 +241,9 @@ def NaiveBayesLearner(dataset):
241241

242242
targetvals = dataset.values[dataset.target]
243243
target_dist = CountingProbDist(targetvals)
244-
attr_dists = dict(((gv, attr), CountingProbDist(dataset.values[attr]))
245-
for gv in targetvals
246-
for attr in dataset.inputs)
244+
attr_dists = {(gv, attr): CountingProbDist(dataset.values[attr])
245+
for gv in targetvals
246+
for attr in dataset.inputs}
247247
for example in dataset.examples:
248248
targetval = example[dataset.target]
249249
target_dist.add(targetval)
@@ -882,9 +882,9 @@ def RestaurantDataSet(examples=None):
882882

883883

884884
def T(attrname, branches):
885-
branches = dict((value, (child if isinstance(child, DecisionFork)
886-
else DecisionLeaf(child)))
887-
for value, child in branches.items())
885+
branches = {value: (child if isinstance(child, DecisionFork)
886+
else DecisionLeaf(child))
887+
for value, child in branches.items()}
888888
return DecisionFork(restaurant.attrnum(attrname), attrname, branches)
889889

890890
""" [Figure 18.2]

‎logic.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -497,8 +497,9 @@ def pl_fc_entails(KB, q):
497497
>>> pl_fc_entails(horn_clauses_KB, expr('Q'))
498498
True
499499
"""
500-
count = dict([(c, len(conjuncts(c.args[0]))) for c in KB.clauses
501-
if c.op == '==>'])
500+
count = {c: len(conjuncts(c.args[0]))
501+
for c in KB.clauses
502+
if c.op == '==>'}
502503
inferred = defaultdict(bool)
503504
agenda = [s for s in KB.clauses if is_prop_symbol(s.op)]
504505
while agenda:
@@ -642,7 +643,7 @@ def WalkSAT(clauses, p=0.5, max_flips=10000):
642643
# set of all symbols in all clauses
643644
symbols = set(sym for clause in clauses for sym in prop_symbols(clause))
644645
# model is a random assignment of true/false to the symbols in clauses
645-
model = dict([(s, random.choice([True, False])) for s in symbols])
646+
model = {s: random.choice([True, False]) for s in symbols}
646647
for i in range(max_flips):
647648
satisfied, unsatisfied = [], []
648649
for clause in clauses:

‎mdp.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,13 +93,14 @@ def to_grid(self, mapping):
9393
def to_arrows(self, policy):
9494
chars = {
9595
(1, 0): '>', (0, 1): '^', (-1, 0): '<', (0, -1): 'v', None: '.'}
96-
return self.to_grid(
97-
dict([(s, chars[a]) for (s, a) in policy.items()]))
96+
return self.to_grid({s: chars[a] for (s, a) in policy.items()})
9897

9998
# ______________________________________________________________________________
99+
100100
""" [Figure 17.1]
101101
A 4x3 grid environment that presents the agent with a sequential decision problem.
102102
"""
103+
103104
sequential_decision_environment = GridMDP([[-0.04, -0.04, -0.04, +1],
104105
[-0.04, None, -0.04, -1],
105106
[-0.04, -0.04, -0.04, -0.04]],
@@ -110,7 +111,7 @@ def to_arrows(self, policy):
110111

111112
def value_iteration(mdp, epsilon=0.001):
112113
"Solving an MDP by value iteration. [Figure 17.4]"
113-
U1 = dict([(s, 0) for s in mdp.states])
114+
U1 = {s: 0 for s in mdp.states}
114115
R, T, gamma = mdp.R, mdp.T, mdp.gamma
115116
while True:
116117
U = U1.copy()
@@ -141,8 +142,8 @@ def expected_utility(a, s, U, mdp):
141142

142143
def policy_iteration(mdp):
143144
"Solve an MDP by policy iteration [Figure 17.7]"
144-
U = dict([(s, 0) for s in mdp.states])
145-
pi = dict([(s, random.choice(mdp.actions(s))) for s in mdp.states])
145+
U = {s: 0 for s in mdp.states}
146+
pi = {s: random.choice(mdp.actions(s)) for s in mdp.states}
146147
while True:
147148
U = policy_evaluation(pi, U, mdp)
148149
unchanged = True

‎probability.py‎

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,7 @@ def __init__(self, X, parents, cpt):
237237
elif isinstance(cpt, dict):
238238
# one parent, 1-tuple
239239
if cpt and isinstance(list(cpt.keys())[0], bool):
240-
cpt = dict(((v,), p) for v, p in cpt.items())
240+
cpt = {(v,): p for v, p in cpt.items()}
241241

242242
assert isinstance(cpt, dict)
243243
for vs, p in cpt.items():
@@ -344,8 +344,8 @@ def make_factor(var, e, bn):
344344
is the pointwise product of these factors for bn's variables."""
345345
node = bn.variable_node(var)
346346
variables = [X for X in [var] + node.parents if X not in e]
347-
cpt = dict((event_values(e1, variables), node.p(e1[var], e1))
348-
for e1 in all_events(variables, bn, e))
347+
cpt = {event_values(e1, variables): node.p(e1[var], e1)
348+
for e1 in all_events(variables, bn, e)}
349349
return Factor(variables, cpt)
350350

351351

@@ -373,24 +373,23 @@ def __init__(self, variables, cpt):
373373
def pointwise_product(self, other, bn):
374374
"Multiply two factors, combining their variables."
375375
variables = list(set(self.variables) | set(other.variables))
376-
cpt = dict((event_values(e, variables), self.p(e) * other.p(e))
377-
for e in all_events(variables, bn, {}))
376+
cpt = {event_values(e, variables): self.p(e) * other.p(e)
377+
for e in all_events(variables, bn, {})}
378378
return Factor(variables, cpt)
379379

380380
def sum_out(self, var, bn):
381381
"Make a factor eliminating var by summing over its values."
382382
variables = [X for X in self.variables if X != var]
383-
cpt = dict((event_values(e, variables),
384-
sum(self.p(extend(e, var, val))
385-
for val in bn.variable_values(var)))
386-
for e in all_events(variables, bn, {}))
383+
cpt = {event_values(e, variables): sum(self.p(extend(e, var, val))
384+
for val in bn.variable_values(var))
385+
for e in all_events(variables, bn, {})}
387386
return Factor(variables, cpt)
388387

389388
def normalize(self):
390389
"Return my probabilities; must be down to one variable."
391390
assert len(self.variables) == 1
392391
return ProbDist(self.variables[0],
393-
dict((k, v) for ((k,), v) in self.cpt.items()))
392+
{k: v for ((k,), v) in self.cpt.items()})
394393

395394
def p(self, e):
396395
"Look up my value tabulated for e."
@@ -442,8 +441,7 @@ def rejection_sampling(X, e, bn, N):
442441
... burglary, 10000).show_approx()
443442
'False: 0.7, True: 0.3'
444443
"""
445-
counts = dict((x, 0)
446-
for x in bn.variable_values(X)) # bold N in [Figure 14.14]
444+
counts = {x: 0 for x in bn.variable_values(X)} # bold N in [Figure 14.14]
447445
for j in range(N):
448446
sample = prior_sample(bn) # boldface x in [Figure 14.14]
449447
if consistent_with(sample, e):
@@ -467,7 +465,7 @@ def likelihood_weighting(X, e, bn, N):
467465
... burglary, 10000).show_approx()
468466
'False: 0.702, True: 0.298'
469467
"""
470-
W = dict((x, 0) for x in bn.variable_values(X))
468+
W = {x: 0 for x in bn.variable_values(X)}
471469
for j in range(N):
472470
sample, weight = weighted_sample(bn, e) # boldface x, w in [Figure 14.15]
473471
W[sample[X]] += weight

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL