partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
valid
|
CSP.suppose
|
Start accumulating inferences from assuming var=value.
|
aima/csp.py
|
def suppose(self, var, value):
"Start accumulating inferences from assuming var=value."
self.support_pruning()
removals = [(var, a) for a in self.curr_domains[var] if a != value]
self.curr_domains[var] = [value]
return removals
|
def suppose(self, var, value):
"Start accumulating inferences from assuming var=value."
self.support_pruning()
removals = [(var, a) for a in self.curr_domains[var] if a != value]
self.curr_domains[var] = [value]
return removals
|
[
"Start",
"accumulating",
"inferences",
"from",
"assuming",
"var",
"=",
"value",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L111-L116
|
[
"def",
"suppose",
"(",
"self",
",",
"var",
",",
"value",
")",
":",
"self",
".",
"support_pruning",
"(",
")",
"removals",
"=",
"[",
"(",
"var",
",",
"a",
")",
"for",
"a",
"in",
"self",
".",
"curr_domains",
"[",
"var",
"]",
"if",
"a",
"!=",
"value",
"]",
"self",
".",
"curr_domains",
"[",
"var",
"]",
"=",
"[",
"value",
"]",
"return",
"removals"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
CSP.prune
|
Rule out var=value.
|
aima/csp.py
|
def prune(self, var, value, removals):
"Rule out var=value."
self.curr_domains[var].remove(value)
if removals is not None: removals.append((var, value))
|
def prune(self, var, value, removals):
"Rule out var=value."
self.curr_domains[var].remove(value)
if removals is not None: removals.append((var, value))
|
[
"Rule",
"out",
"var",
"=",
"value",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L118-L121
|
[
"def",
"prune",
"(",
"self",
",",
"var",
",",
"value",
",",
"removals",
")",
":",
"self",
".",
"curr_domains",
"[",
"var",
"]",
".",
"remove",
"(",
"value",
")",
"if",
"removals",
"is",
"not",
"None",
":",
"removals",
".",
"append",
"(",
"(",
"var",
",",
"value",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
CSP.infer_assignment
|
Return the partial assignment implied by the current inferences.
|
aima/csp.py
|
def infer_assignment(self):
"Return the partial assignment implied by the current inferences."
self.support_pruning()
return dict((v, self.curr_domains[v][0])
for v in self.vars if 1 == len(self.curr_domains[v]))
|
def infer_assignment(self):
"Return the partial assignment implied by the current inferences."
self.support_pruning()
return dict((v, self.curr_domains[v][0])
for v in self.vars if 1 == len(self.curr_domains[v]))
|
[
"Return",
"the",
"partial",
"assignment",
"implied",
"by",
"the",
"current",
"inferences",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L127-L131
|
[
"def",
"infer_assignment",
"(",
"self",
")",
":",
"self",
".",
"support_pruning",
"(",
")",
"return",
"dict",
"(",
"(",
"v",
",",
"self",
".",
"curr_domains",
"[",
"v",
"]",
"[",
"0",
"]",
")",
"for",
"v",
"in",
"self",
".",
"vars",
"if",
"1",
"==",
"len",
"(",
"self",
".",
"curr_domains",
"[",
"v",
"]",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
CSP.restore
|
Undo a supposition and all inferences from it.
|
aima/csp.py
|
def restore(self, removals):
"Undo a supposition and all inferences from it."
for B, b in removals:
self.curr_domains[B].append(b)
|
def restore(self, removals):
"Undo a supposition and all inferences from it."
for B, b in removals:
self.curr_domains[B].append(b)
|
[
"Undo",
"a",
"supposition",
"and",
"all",
"inferences",
"from",
"it",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L133-L136
|
[
"def",
"restore",
"(",
"self",
",",
"removals",
")",
":",
"for",
"B",
",",
"b",
"in",
"removals",
":",
"self",
".",
"curr_domains",
"[",
"B",
"]",
".",
"append",
"(",
"b",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
CSP.conflicted_vars
|
Return a list of variables in current assignment that are in conflict
|
aima/csp.py
|
def conflicted_vars(self, current):
"Return a list of variables in current assignment that are in conflict"
return [var for var in self.vars
if self.nconflicts(var, current[var], current) > 0]
|
def conflicted_vars(self, current):
"Return a list of variables in current assignment that are in conflict"
return [var for var in self.vars
if self.nconflicts(var, current[var], current) > 0]
|
[
"Return",
"a",
"list",
"of",
"variables",
"in",
"current",
"assignment",
"that",
"are",
"in",
"conflict"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L140-L143
|
[
"def",
"conflicted_vars",
"(",
"self",
",",
"current",
")",
":",
"return",
"[",
"var",
"for",
"var",
"in",
"self",
".",
"vars",
"if",
"self",
".",
"nconflicts",
"(",
"var",
",",
"current",
"[",
"var",
"]",
",",
"current",
")",
">",
"0",
"]"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NQueensCSP.nconflicts
|
The number of conflicts, as recorded with each assignment.
Count conflicts in row and in up, down diagonals. If there
is a queen there, it can't conflict with itself, so subtract 3.
|
aima/csp.py
|
def nconflicts(self, var, val, assignment):
"""The number of conflicts, as recorded with each assignment.
Count conflicts in row and in up, down diagonals. If there
is a queen there, it can't conflict with itself, so subtract 3."""
n = len(self.vars)
c = self.rows[val] + self.downs[var+val] + self.ups[var-val+n-1]
if assignment.get(var, None) == val:
c -= 3
return c
|
def nconflicts(self, var, val, assignment):
"""The number of conflicts, as recorded with each assignment.
Count conflicts in row and in up, down diagonals. If there
is a queen there, it can't conflict with itself, so subtract 3."""
n = len(self.vars)
c = self.rows[val] + self.downs[var+val] + self.ups[var-val+n-1]
if assignment.get(var, None) == val:
c -= 3
return c
|
[
"The",
"number",
"of",
"conflicts",
"as",
"recorded",
"with",
"each",
"assignment",
".",
"Count",
"conflicts",
"in",
"row",
"and",
"in",
"up",
"down",
"diagonals",
".",
"If",
"there",
"is",
"a",
"queen",
"there",
"it",
"can",
"t",
"conflict",
"with",
"itself",
"so",
"subtract",
"3",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L422-L430
|
[
"def",
"nconflicts",
"(",
"self",
",",
"var",
",",
"val",
",",
"assignment",
")",
":",
"n",
"=",
"len",
"(",
"self",
".",
"vars",
")",
"c",
"=",
"self",
".",
"rows",
"[",
"val",
"]",
"+",
"self",
".",
"downs",
"[",
"var",
"+",
"val",
"]",
"+",
"self",
".",
"ups",
"[",
"var",
"-",
"val",
"+",
"n",
"-",
"1",
"]",
"if",
"assignment",
".",
"get",
"(",
"var",
",",
"None",
")",
"==",
"val",
":",
"c",
"-=",
"3",
"return",
"c"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NQueensCSP.assign
|
Assign var, and keep track of conflicts.
|
aima/csp.py
|
def assign(self, var, val, assignment):
"Assign var, and keep track of conflicts."
oldval = assignment.get(var, None)
if val != oldval:
if oldval is not None: # Remove old val if there was one
self.record_conflict(assignment, var, oldval, -1)
self.record_conflict(assignment, var, val, +1)
CSP.assign(self, var, val, assignment)
|
def assign(self, var, val, assignment):
"Assign var, and keep track of conflicts."
oldval = assignment.get(var, None)
if val != oldval:
if oldval is not None: # Remove old val if there was one
self.record_conflict(assignment, var, oldval, -1)
self.record_conflict(assignment, var, val, +1)
CSP.assign(self, var, val, assignment)
|
[
"Assign",
"var",
"and",
"keep",
"track",
"of",
"conflicts",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L432-L439
|
[
"def",
"assign",
"(",
"self",
",",
"var",
",",
"val",
",",
"assignment",
")",
":",
"oldval",
"=",
"assignment",
".",
"get",
"(",
"var",
",",
"None",
")",
"if",
"val",
"!=",
"oldval",
":",
"if",
"oldval",
"is",
"not",
"None",
":",
"# Remove old val if there was one",
"self",
".",
"record_conflict",
"(",
"assignment",
",",
"var",
",",
"oldval",
",",
"-",
"1",
")",
"self",
".",
"record_conflict",
"(",
"assignment",
",",
"var",
",",
"val",
",",
"+",
"1",
")",
"CSP",
".",
"assign",
"(",
"self",
",",
"var",
",",
"val",
",",
"assignment",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NQueensCSP.unassign
|
Remove var from assignment (if it is there) and track conflicts.
|
aima/csp.py
|
def unassign(self, var, assignment):
"Remove var from assignment (if it is there) and track conflicts."
if var in assignment:
self.record_conflict(assignment, var, assignment[var], -1)
CSP.unassign(self, var, assignment)
|
def unassign(self, var, assignment):
"Remove var from assignment (if it is there) and track conflicts."
if var in assignment:
self.record_conflict(assignment, var, assignment[var], -1)
CSP.unassign(self, var, assignment)
|
[
"Remove",
"var",
"from",
"assignment",
"(",
"if",
"it",
"is",
"there",
")",
"and",
"track",
"conflicts",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L441-L445
|
[
"def",
"unassign",
"(",
"self",
",",
"var",
",",
"assignment",
")",
":",
"if",
"var",
"in",
"assignment",
":",
"self",
".",
"record_conflict",
"(",
"assignment",
",",
"var",
",",
"assignment",
"[",
"var",
"]",
",",
"-",
"1",
")",
"CSP",
".",
"unassign",
"(",
"self",
",",
"var",
",",
"assignment",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NQueensCSP.record_conflict
|
Record conflicts caused by addition or deletion of a Queen.
|
aima/csp.py
|
def record_conflict(self, assignment, var, val, delta):
"Record conflicts caused by addition or deletion of a Queen."
n = len(self.vars)
self.rows[val] += delta
self.downs[var + val] += delta
self.ups[var - val + n - 1] += delta
|
def record_conflict(self, assignment, var, val, delta):
"Record conflicts caused by addition or deletion of a Queen."
n = len(self.vars)
self.rows[val] += delta
self.downs[var + val] += delta
self.ups[var - val + n - 1] += delta
|
[
"Record",
"conflicts",
"caused",
"by",
"addition",
"or",
"deletion",
"of",
"a",
"Queen",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L447-L452
|
[
"def",
"record_conflict",
"(",
"self",
",",
"assignment",
",",
"var",
",",
"val",
",",
"delta",
")",
":",
"n",
"=",
"len",
"(",
"self",
".",
"vars",
")",
"self",
".",
"rows",
"[",
"val",
"]",
"+=",
"delta",
"self",
".",
"downs",
"[",
"var",
"+",
"val",
"]",
"+=",
"delta",
"self",
".",
"ups",
"[",
"var",
"-",
"val",
"+",
"n",
"-",
"1",
"]",
"+=",
"delta"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NQueensCSP.display
|
Print the queens and the nconflicts values (for debugging).
|
aima/csp.py
|
def display(self, assignment):
"Print the queens and the nconflicts values (for debugging)."
n = len(self.vars)
for val in range(n):
for var in range(n):
if assignment.get(var,'') == val: ch = 'Q'
elif (var+val) % 2 == 0: ch = '.'
else: ch = '-'
print ch,
print ' ',
for var in range(n):
if assignment.get(var,'') == val: ch = '*'
else: ch = ' '
print str(self.nconflicts(var, val, assignment))+ch,
print
|
def display(self, assignment):
"Print the queens and the nconflicts values (for debugging)."
n = len(self.vars)
for val in range(n):
for var in range(n):
if assignment.get(var,'') == val: ch = 'Q'
elif (var+val) % 2 == 0: ch = '.'
else: ch = '-'
print ch,
print ' ',
for var in range(n):
if assignment.get(var,'') == val: ch = '*'
else: ch = ' '
print str(self.nconflicts(var, val, assignment))+ch,
print
|
[
"Print",
"the",
"queens",
"and",
"the",
"nconflicts",
"values",
"(",
"for",
"debugging",
")",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L454-L468
|
[
"def",
"display",
"(",
"self",
",",
"assignment",
")",
":",
"n",
"=",
"len",
"(",
"self",
".",
"vars",
")",
"for",
"val",
"in",
"range",
"(",
"n",
")",
":",
"for",
"var",
"in",
"range",
"(",
"n",
")",
":",
"if",
"assignment",
".",
"get",
"(",
"var",
",",
"''",
")",
"==",
"val",
":",
"ch",
"=",
"'Q'",
"elif",
"(",
"var",
"+",
"val",
")",
"%",
"2",
"==",
"0",
":",
"ch",
"=",
"'.'",
"else",
":",
"ch",
"=",
"'-'",
"print",
"ch",
",",
"print",
"' '",
",",
"for",
"var",
"in",
"range",
"(",
"n",
")",
":",
"if",
"assignment",
".",
"get",
"(",
"var",
",",
"''",
")",
"==",
"val",
":",
"ch",
"=",
"'*'",
"else",
":",
"ch",
"=",
"' '",
"print",
"str",
"(",
"self",
".",
"nconflicts",
"(",
"var",
",",
"val",
",",
"assignment",
")",
")",
"+",
"ch",
",",
"print"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
viterbi_segment
|
Find the best segmentation of the string of characters, given the
UnigramTextModel P.
|
aima/text.py
|
def viterbi_segment(text, P):
"""Find the best segmentation of the string of characters, given the
UnigramTextModel P."""
# best[i] = best probability for text[0:i]
# words[i] = best word ending at position i
n = len(text)
words = [''] + list(text)
best = [1.0] + [0.0] * n
## Fill in the vectors best, words via dynamic programming
for i in range(n+1):
for j in range(0, i):
w = text[j:i]
if P[w] * best[i - len(w)] >= best[i]:
best[i] = P[w] * best[i - len(w)]
words[i] = w
## Now recover the sequence of best words
sequence = []; i = len(words)-1
while i > 0:
sequence[0:0] = [words[i]]
i = i - len(words[i])
## Return sequence of best words and overall probability
return sequence, best[-1]
|
def viterbi_segment(text, P):
"""Find the best segmentation of the string of characters, given the
UnigramTextModel P."""
# best[i] = best probability for text[0:i]
# words[i] = best word ending at position i
n = len(text)
words = [''] + list(text)
best = [1.0] + [0.0] * n
## Fill in the vectors best, words via dynamic programming
for i in range(n+1):
for j in range(0, i):
w = text[j:i]
if P[w] * best[i - len(w)] >= best[i]:
best[i] = P[w] * best[i - len(w)]
words[i] = w
## Now recover the sequence of best words
sequence = []; i = len(words)-1
while i > 0:
sequence[0:0] = [words[i]]
i = i - len(words[i])
## Return sequence of best words and overall probability
return sequence, best[-1]
|
[
"Find",
"the",
"best",
"segmentation",
"of",
"the",
"string",
"of",
"characters",
"given",
"the",
"UnigramTextModel",
"P",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L67-L88
|
[
"def",
"viterbi_segment",
"(",
"text",
",",
"P",
")",
":",
"# best[i] = best probability for text[0:i]",
"# words[i] = best word ending at position i",
"n",
"=",
"len",
"(",
"text",
")",
"words",
"=",
"[",
"''",
"]",
"+",
"list",
"(",
"text",
")",
"best",
"=",
"[",
"1.0",
"]",
"+",
"[",
"0.0",
"]",
"*",
"n",
"## Fill in the vectors best, words via dynamic programming",
"for",
"i",
"in",
"range",
"(",
"n",
"+",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"i",
")",
":",
"w",
"=",
"text",
"[",
"j",
":",
"i",
"]",
"if",
"P",
"[",
"w",
"]",
"*",
"best",
"[",
"i",
"-",
"len",
"(",
"w",
")",
"]",
">=",
"best",
"[",
"i",
"]",
":",
"best",
"[",
"i",
"]",
"=",
"P",
"[",
"w",
"]",
"*",
"best",
"[",
"i",
"-",
"len",
"(",
"w",
")",
"]",
"words",
"[",
"i",
"]",
"=",
"w",
"## Now recover the sequence of best words",
"sequence",
"=",
"[",
"]",
"i",
"=",
"len",
"(",
"words",
")",
"-",
"1",
"while",
"i",
">",
"0",
":",
"sequence",
"[",
"0",
":",
"0",
"]",
"=",
"[",
"words",
"[",
"i",
"]",
"]",
"i",
"=",
"i",
"-",
"len",
"(",
"words",
"[",
"i",
"]",
")",
"## Return sequence of best words and overall probability",
"return",
"sequence",
",",
"best",
"[",
"-",
"1",
"]"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
encode
|
Encodes text, using a code which is a permutation of the alphabet.
|
aima/text.py
|
def encode(plaintext, code):
"Encodes text, using a code which is a permutation of the alphabet."
from string import maketrans
trans = maketrans(alphabet + alphabet.upper(), code + code.upper())
return plaintext.translate(trans)
|
def encode(plaintext, code):
"Encodes text, using a code which is a permutation of the alphabet."
from string import maketrans
trans = maketrans(alphabet + alphabet.upper(), code + code.upper())
return plaintext.translate(trans)
|
[
"Encodes",
"text",
"using",
"a",
"code",
"which",
"is",
"a",
"permutation",
"of",
"the",
"alphabet",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L213-L217
|
[
"def",
"encode",
"(",
"plaintext",
",",
"code",
")",
":",
"from",
"string",
"import",
"maketrans",
"trans",
"=",
"maketrans",
"(",
"alphabet",
"+",
"alphabet",
".",
"upper",
"(",
")",
",",
"code",
"+",
"code",
".",
"upper",
"(",
")",
")",
"return",
"plaintext",
".",
"translate",
"(",
"trans",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NgramTextModel.add
|
Count 1 for P[(w1, ..., wn)] and for P(wn | (w1, ..., wn-1)
|
aima/text.py
|
def add(self, ngram):
"""Count 1 for P[(w1, ..., wn)] and for P(wn | (w1, ..., wn-1)"""
CountingProbDist.add(self, ngram)
self.cond_prob[ngram[:-1]].add(ngram[-1])
|
def add(self, ngram):
"""Count 1 for P[(w1, ..., wn)] and for P(wn | (w1, ..., wn-1)"""
CountingProbDist.add(self, ngram)
self.cond_prob[ngram[:-1]].add(ngram[-1])
|
[
"Count",
"1",
"for",
"P",
"[",
"(",
"w1",
"...",
"wn",
")",
"]",
"and",
"for",
"P",
"(",
"wn",
"|",
"(",
"w1",
"...",
"wn",
"-",
"1",
")"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L37-L40
|
[
"def",
"add",
"(",
"self",
",",
"ngram",
")",
":",
"CountingProbDist",
".",
"add",
"(",
"self",
",",
"ngram",
")",
"self",
".",
"cond_prob",
"[",
"ngram",
"[",
":",
"-",
"1",
"]",
"]",
".",
"add",
"(",
"ngram",
"[",
"-",
"1",
"]",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NgramTextModel.add_sequence
|
Add each of the tuple words[i:i+n], using a sliding window.
Prefix some copies of the empty word, '', to make the start work.
|
aima/text.py
|
def add_sequence(self, words):
"""Add each of the tuple words[i:i+n], using a sliding window.
Prefix some copies of the empty word, '', to make the start work."""
n = self.n
words = ['',] * (n-1) + words
for i in range(len(words)-n):
self.add(tuple(words[i:i+n]))
|
def add_sequence(self, words):
"""Add each of the tuple words[i:i+n], using a sliding window.
Prefix some copies of the empty word, '', to make the start work."""
n = self.n
words = ['',] * (n-1) + words
for i in range(len(words)-n):
self.add(tuple(words[i:i+n]))
|
[
"Add",
"each",
"of",
"the",
"tuple",
"words",
"[",
"i",
":",
"i",
"+",
"n",
"]",
"using",
"a",
"sliding",
"window",
".",
"Prefix",
"some",
"copies",
"of",
"the",
"empty",
"word",
"to",
"make",
"the",
"start",
"work",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L42-L48
|
[
"def",
"add_sequence",
"(",
"self",
",",
"words",
")",
":",
"n",
"=",
"self",
".",
"n",
"words",
"=",
"[",
"''",
",",
"]",
"*",
"(",
"n",
"-",
"1",
")",
"+",
"words",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"words",
")",
"-",
"n",
")",
":",
"self",
".",
"add",
"(",
"tuple",
"(",
"words",
"[",
"i",
":",
"i",
"+",
"n",
"]",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NgramTextModel.samples
|
Build up a random sample of text nwords words long, using
the conditional probability given the n-1 preceding words.
|
aima/text.py
|
def samples(self, nwords):
"""Build up a random sample of text nwords words long, using
the conditional probability given the n-1 preceding words."""
n = self.n
nminus1gram = ('',) * (n-1)
output = []
for i in range(nwords):
if nminus1gram not in self.cond_prob:
nminus1gram = ('',) * (n-1) # Cannot continue, so restart.
wn = self.cond_prob[nminus1gram].sample()
output.append(wn)
nminus1gram = nminus1gram[1:] + (wn,)
return ' '.join(output)
|
def samples(self, nwords):
"""Build up a random sample of text nwords words long, using
the conditional probability given the n-1 preceding words."""
n = self.n
nminus1gram = ('',) * (n-1)
output = []
for i in range(nwords):
if nminus1gram not in self.cond_prob:
nminus1gram = ('',) * (n-1) # Cannot continue, so restart.
wn = self.cond_prob[nminus1gram].sample()
output.append(wn)
nminus1gram = nminus1gram[1:] + (wn,)
return ' '.join(output)
|
[
"Build",
"up",
"a",
"random",
"sample",
"of",
"text",
"nwords",
"words",
"long",
"using",
"the",
"conditional",
"probability",
"given",
"the",
"n",
"-",
"1",
"preceding",
"words",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L50-L62
|
[
"def",
"samples",
"(",
"self",
",",
"nwords",
")",
":",
"n",
"=",
"self",
".",
"n",
"nminus1gram",
"=",
"(",
"''",
",",
")",
"*",
"(",
"n",
"-",
"1",
")",
"output",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"nwords",
")",
":",
"if",
"nminus1gram",
"not",
"in",
"self",
".",
"cond_prob",
":",
"nminus1gram",
"=",
"(",
"''",
",",
")",
"*",
"(",
"n",
"-",
"1",
")",
"# Cannot continue, so restart.",
"wn",
"=",
"self",
".",
"cond_prob",
"[",
"nminus1gram",
"]",
".",
"sample",
"(",
")",
"output",
".",
"append",
"(",
"wn",
")",
"nminus1gram",
"=",
"nminus1gram",
"[",
"1",
":",
"]",
"+",
"(",
"wn",
",",
")",
"return",
"' '",
".",
"join",
"(",
"output",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
IRSystem.index_collection
|
Index a whole collection of files.
|
aima/text.py
|
def index_collection(self, filenames):
"Index a whole collection of files."
for filename in filenames:
self.index_document(open(filename).read(), filename)
|
def index_collection(self, filenames):
"Index a whole collection of files."
for filename in filenames:
self.index_document(open(filename).read(), filename)
|
[
"Index",
"a",
"whole",
"collection",
"of",
"files",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L110-L113
|
[
"def",
"index_collection",
"(",
"self",
",",
"filenames",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"self",
".",
"index_document",
"(",
"open",
"(",
"filename",
")",
".",
"read",
"(",
")",
",",
"filename",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
IRSystem.index_document
|
Index the text of a document.
|
aima/text.py
|
def index_document(self, text, url):
"Index the text of a document."
## For now, use first line for title
title = text[:text.index('\n')].strip()
docwords = words(text)
docid = len(self.documents)
self.documents.append(Document(title, url, len(docwords)))
for word in docwords:
if word not in self.stopwords:
self.index[word][docid] += 1
|
def index_document(self, text, url):
"Index the text of a document."
## For now, use first line for title
title = text[:text.index('\n')].strip()
docwords = words(text)
docid = len(self.documents)
self.documents.append(Document(title, url, len(docwords)))
for word in docwords:
if word not in self.stopwords:
self.index[word][docid] += 1
|
[
"Index",
"the",
"text",
"of",
"a",
"document",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L115-L124
|
[
"def",
"index_document",
"(",
"self",
",",
"text",
",",
"url",
")",
":",
"## For now, use first line for title",
"title",
"=",
"text",
"[",
":",
"text",
".",
"index",
"(",
"'\\n'",
")",
"]",
".",
"strip",
"(",
")",
"docwords",
"=",
"words",
"(",
"text",
")",
"docid",
"=",
"len",
"(",
"self",
".",
"documents",
")",
"self",
".",
"documents",
".",
"append",
"(",
"Document",
"(",
"title",
",",
"url",
",",
"len",
"(",
"docwords",
")",
")",
")",
"for",
"word",
"in",
"docwords",
":",
"if",
"word",
"not",
"in",
"self",
".",
"stopwords",
":",
"self",
".",
"index",
"[",
"word",
"]",
"[",
"docid",
"]",
"+=",
"1"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
IRSystem.query
|
Return a list of n (score, docid) pairs for the best matches.
Also handle the special syntax for 'learn: command'.
|
aima/text.py
|
def query(self, query_text, n=10):
"""Return a list of n (score, docid) pairs for the best matches.
Also handle the special syntax for 'learn: command'."""
if query_text.startswith("learn:"):
doctext = os.popen(query_text[len("learn:"):], 'r').read()
self.index_document(doctext, query_text)
return []
qwords = [w for w in words(query_text) if w not in self.stopwords]
shortest = argmin(qwords, lambda w: len(self.index[w]))
docs = self.index[shortest]
results = [(sum([self.score(w, d) for w in qwords]), d) for d in docs]
results.sort(); results.reverse()
return results[:n]
|
def query(self, query_text, n=10):
"""Return a list of n (score, docid) pairs for the best matches.
Also handle the special syntax for 'learn: command'."""
if query_text.startswith("learn:"):
doctext = os.popen(query_text[len("learn:"):], 'r').read()
self.index_document(doctext, query_text)
return []
qwords = [w for w in words(query_text) if w not in self.stopwords]
shortest = argmin(qwords, lambda w: len(self.index[w]))
docs = self.index[shortest]
results = [(sum([self.score(w, d) for w in qwords]), d) for d in docs]
results.sort(); results.reverse()
return results[:n]
|
[
"Return",
"a",
"list",
"of",
"n",
"(",
"score",
"docid",
")",
"pairs",
"for",
"the",
"best",
"matches",
".",
"Also",
"handle",
"the",
"special",
"syntax",
"for",
"learn",
":",
"command",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L126-L138
|
[
"def",
"query",
"(",
"self",
",",
"query_text",
",",
"n",
"=",
"10",
")",
":",
"if",
"query_text",
".",
"startswith",
"(",
"\"learn:\"",
")",
":",
"doctext",
"=",
"os",
".",
"popen",
"(",
"query_text",
"[",
"len",
"(",
"\"learn:\"",
")",
":",
"]",
",",
"'r'",
")",
".",
"read",
"(",
")",
"self",
".",
"index_document",
"(",
"doctext",
",",
"query_text",
")",
"return",
"[",
"]",
"qwords",
"=",
"[",
"w",
"for",
"w",
"in",
"words",
"(",
"query_text",
")",
"if",
"w",
"not",
"in",
"self",
".",
"stopwords",
"]",
"shortest",
"=",
"argmin",
"(",
"qwords",
",",
"lambda",
"w",
":",
"len",
"(",
"self",
".",
"index",
"[",
"w",
"]",
")",
")",
"docs",
"=",
"self",
".",
"index",
"[",
"shortest",
"]",
"results",
"=",
"[",
"(",
"sum",
"(",
"[",
"self",
".",
"score",
"(",
"w",
",",
"d",
")",
"for",
"w",
"in",
"qwords",
"]",
")",
",",
"d",
")",
"for",
"d",
"in",
"docs",
"]",
"results",
".",
"sort",
"(",
")",
"results",
".",
"reverse",
"(",
")",
"return",
"results",
"[",
":",
"n",
"]"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
IRSystem.score
|
Compute a score for this word on this docid.
|
aima/text.py
|
def score(self, word, docid):
"Compute a score for this word on this docid."
## There are many options; here we take a very simple approach
return (math.log(1 + self.index[word][docid])
/ math.log(1 + self.documents[docid].nwords))
|
def score(self, word, docid):
"Compute a score for this word on this docid."
## There are many options; here we take a very simple approach
return (math.log(1 + self.index[word][docid])
/ math.log(1 + self.documents[docid].nwords))
|
[
"Compute",
"a",
"score",
"for",
"this",
"word",
"on",
"this",
"docid",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L140-L144
|
[
"def",
"score",
"(",
"self",
",",
"word",
",",
"docid",
")",
":",
"## There are many options; here we take a very simple approach",
"return",
"(",
"math",
".",
"log",
"(",
"1",
"+",
"self",
".",
"index",
"[",
"word",
"]",
"[",
"docid",
"]",
")",
"/",
"math",
".",
"log",
"(",
"1",
"+",
"self",
".",
"documents",
"[",
"docid",
"]",
".",
"nwords",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
IRSystem.present
|
Present the results as a list.
|
aima/text.py
|
def present(self, results):
"Present the results as a list."
for (score, d) in results:
doc = self.documents[d]
print ("%5.2f|%25s | %s"
% (100 * score, doc.url, doc.title[:45].expandtabs()))
|
def present(self, results):
"Present the results as a list."
for (score, d) in results:
doc = self.documents[d]
print ("%5.2f|%25s | %s"
% (100 * score, doc.url, doc.title[:45].expandtabs()))
|
[
"Present",
"the",
"results",
"as",
"a",
"list",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L146-L151
|
[
"def",
"present",
"(",
"self",
",",
"results",
")",
":",
"for",
"(",
"score",
",",
"d",
")",
"in",
"results",
":",
"doc",
"=",
"self",
".",
"documents",
"[",
"d",
"]",
"print",
"(",
"\"%5.2f|%25s | %s\"",
"%",
"(",
"100",
"*",
"score",
",",
"doc",
".",
"url",
",",
"doc",
".",
"title",
"[",
":",
"45",
"]",
".",
"expandtabs",
"(",
")",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
IRSystem.present_results
|
Get results for the query and present them.
|
aima/text.py
|
def present_results(self, query_text, n=10):
"Get results for the query and present them."
self.present(self.query(query_text, n))
|
def present_results(self, query_text, n=10):
"Get results for the query and present them."
self.present(self.query(query_text, n))
|
[
"Get",
"results",
"for",
"the",
"query",
"and",
"present",
"them",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L153-L155
|
[
"def",
"present_results",
"(",
"self",
",",
"query_text",
",",
"n",
"=",
"10",
")",
":",
"self",
".",
"present",
"(",
"self",
".",
"query",
"(",
"query_text",
",",
"n",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
ShiftDecoder.score
|
Return a score for text based on how common letters pairs are.
|
aima/text.py
|
def score(self, plaintext):
"Return a score for text based on how common letters pairs are."
s = 1.0
for bi in bigrams(plaintext):
s = s * self.P2[bi]
return s
|
def score(self, plaintext):
"Return a score for text based on how common letters pairs are."
s = 1.0
for bi in bigrams(plaintext):
s = s * self.P2[bi]
return s
|
[
"Return",
"a",
"score",
"for",
"text",
"based",
"on",
"how",
"common",
"letters",
"pairs",
"are",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L240-L245
|
[
"def",
"score",
"(",
"self",
",",
"plaintext",
")",
":",
"s",
"=",
"1.0",
"for",
"bi",
"in",
"bigrams",
"(",
"plaintext",
")",
":",
"s",
"=",
"s",
"*",
"self",
".",
"P2",
"[",
"bi",
"]",
"return",
"s"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
PermutationDecoder.decode
|
Search for a decoding of the ciphertext.
|
aima/text.py
|
def decode(self, ciphertext):
"Search for a decoding of the ciphertext."
self.ciphertext = ciphertext
problem = PermutationDecoderProblem(decoder=self)
return search.best_first_tree_search(
problem, lambda node: self.score(node.state))
|
def decode(self, ciphertext):
"Search for a decoding of the ciphertext."
self.ciphertext = ciphertext
problem = PermutationDecoderProblem(decoder=self)
return search.best_first_tree_search(
problem, lambda node: self.score(node.state))
|
[
"Search",
"for",
"a",
"decoding",
"of",
"the",
"ciphertext",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L276-L281
|
[
"def",
"decode",
"(",
"self",
",",
"ciphertext",
")",
":",
"self",
".",
"ciphertext",
"=",
"ciphertext",
"problem",
"=",
"PermutationDecoderProblem",
"(",
"decoder",
"=",
"self",
")",
"return",
"search",
".",
"best_first_tree_search",
"(",
"problem",
",",
"lambda",
"node",
":",
"self",
".",
"score",
"(",
"node",
".",
"state",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
PermutationDecoder.score
|
Score is product of word scores, unigram scores, and bigram scores.
This can get very small, so we use logs and exp.
|
aima/text.py
|
def score(self, code):
"""Score is product of word scores, unigram scores, and bigram scores.
This can get very small, so we use logs and exp."""
text = permutation_decode(self.ciphertext, code)
logP = (sum([log(self.Pwords[word]) for word in words(text)]) +
sum([log(self.P1[c]) for c in text]) +
sum([log(self.P2[b]) for b in bigrams(text)]))
return exp(logP)
|
def score(self, code):
"""Score is product of word scores, unigram scores, and bigram scores.
This can get very small, so we use logs and exp."""
text = permutation_decode(self.ciphertext, code)
logP = (sum([log(self.Pwords[word]) for word in words(text)]) +
sum([log(self.P1[c]) for c in text]) +
sum([log(self.P2[b]) for b in bigrams(text)]))
return exp(logP)
|
[
"Score",
"is",
"product",
"of",
"word",
"scores",
"unigram",
"scores",
"and",
"bigram",
"scores",
".",
"This",
"can",
"get",
"very",
"small",
"so",
"we",
"use",
"logs",
"and",
"exp",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L283-L290
|
[
"def",
"score",
"(",
"self",
",",
"code",
")",
":",
"text",
"=",
"permutation_decode",
"(",
"self",
".",
"ciphertext",
",",
"code",
")",
"logP",
"=",
"(",
"sum",
"(",
"[",
"log",
"(",
"self",
".",
"Pwords",
"[",
"word",
"]",
")",
"for",
"word",
"in",
"words",
"(",
"text",
")",
"]",
")",
"+",
"sum",
"(",
"[",
"log",
"(",
"self",
".",
"P1",
"[",
"c",
"]",
")",
"for",
"c",
"in",
"text",
"]",
")",
"+",
"sum",
"(",
"[",
"log",
"(",
"self",
".",
"P2",
"[",
"b",
"]",
")",
"for",
"b",
"in",
"bigrams",
"(",
"text",
")",
"]",
")",
")",
"return",
"exp",
"(",
"logP",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
GetSettings.get_value
|
Returns a ``SettingDict`` object.
|
model_settings/templatetags/model_settings_tags.py
|
def get_value(self, context, default):
"""
Returns a ``SettingDict`` object.
"""
if default is None:
settings = self.setting_model.objects.as_dict()
else:
settings = self.setting_model.objects.as_dict(default=default)
return settings
|
def get_value(self, context, default):
"""
Returns a ``SettingDict`` object.
"""
if default is None:
settings = self.setting_model.objects.as_dict()
else:
settings = self.setting_model.objects.as_dict(default=default)
return settings
|
[
"Returns",
"a",
"SettingDict",
"object",
"."
] |
ixc/django-model-settings
|
python
|
https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/templatetags/model_settings_tags.py#L33-L41
|
[
"def",
"get_value",
"(",
"self",
",",
"context",
",",
"default",
")",
":",
"if",
"default",
"is",
"None",
":",
"settings",
"=",
"self",
".",
"setting_model",
".",
"objects",
".",
"as_dict",
"(",
")",
"else",
":",
"settings",
"=",
"self",
".",
"setting_model",
".",
"objects",
".",
"as_dict",
"(",
"default",
"=",
"default",
")",
"return",
"settings"
] |
654233bf7f13619e4531741f9158e7034eac031b
|
valid
|
GetSetting.get_value
|
Returns the value of the named setting.
|
model_settings/templatetags/model_settings_tags.py
|
def get_value(self, context, name, default):
"""
Returns the value of the named setting.
"""
settings = self.setting_model.objects.filter(name=name)
if default is None:
settings = settings.as_dict()
else:
settings = settings.as_dict(default=default)
value = settings[name]
return value
|
def get_value(self, context, name, default):
"""
Returns the value of the named setting.
"""
settings = self.setting_model.objects.filter(name=name)
if default is None:
settings = settings.as_dict()
else:
settings = settings.as_dict(default=default)
value = settings[name]
return value
|
[
"Returns",
"the",
"value",
"of",
"the",
"named",
"setting",
"."
] |
ixc/django-model-settings
|
python
|
https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/templatetags/model_settings_tags.py#L68-L78
|
[
"def",
"get_value",
"(",
"self",
",",
"context",
",",
"name",
",",
"default",
")",
":",
"settings",
"=",
"self",
".",
"setting_model",
".",
"objects",
".",
"filter",
"(",
"name",
"=",
"name",
")",
"if",
"default",
"is",
"None",
":",
"settings",
"=",
"settings",
".",
"as_dict",
"(",
")",
"else",
":",
"settings",
"=",
"settings",
".",
"as_dict",
"(",
"default",
"=",
"default",
")",
"value",
"=",
"settings",
"[",
"name",
"]",
"return",
"value"
] |
654233bf7f13619e4531741f9158e7034eac031b
|
valid
|
BlockSetting.render_tag
|
Returns the value of the named setting.
|
model_settings/templatetags/model_settings_tags.py
|
def render_tag(self, context, name, nodelist):
"""
Returns the value of the named setting.
"""
# Use `try` and `except` instead of `setdefault()` so we can skip
# rendering the nodelist when the setting already exists.
settings = self.setting_model.objects.filter(name=name).as_dict()
try:
value = settings[name]
except KeyError:
value = settings[name] = nodelist.render(context)
return value
|
def render_tag(self, context, name, nodelist):
"""
Returns the value of the named setting.
"""
# Use `try` and `except` instead of `setdefault()` so we can skip
# rendering the nodelist when the setting already exists.
settings = self.setting_model.objects.filter(name=name).as_dict()
try:
value = settings[name]
except KeyError:
value = settings[name] = nodelist.render(context)
return value
|
[
"Returns",
"the",
"value",
"of",
"the",
"named",
"setting",
"."
] |
ixc/django-model-settings
|
python
|
https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/templatetags/model_settings_tags.py#L102-L113
|
[
"def",
"render_tag",
"(",
"self",
",",
"context",
",",
"name",
",",
"nodelist",
")",
":",
"# Use `try` and `except` instead of `setdefault()` so we can skip",
"# rendering the nodelist when the setting already exists.",
"settings",
"=",
"self",
".",
"setting_model",
".",
"objects",
".",
"filter",
"(",
"name",
"=",
"name",
")",
".",
"as_dict",
"(",
")",
"try",
":",
"value",
"=",
"settings",
"[",
"name",
"]",
"except",
"KeyError",
":",
"value",
"=",
"settings",
"[",
"name",
"]",
"=",
"nodelist",
".",
"render",
"(",
"context",
")",
"return",
"value"
] |
654233bf7f13619e4531741f9158e7034eac031b
|
valid
|
value_iteration
|
Solving an MDP by value iteration. [Fig. 17.4]
|
aima/mdp.py
|
def value_iteration(mdp, epsilon=0.001):
"Solving an MDP by value iteration. [Fig. 17.4]"
U1 = dict([(s, 0) for s in mdp.states])
R, T, gamma = mdp.R, mdp.T, mdp.gamma
while True:
U = U1.copy()
delta = 0
for s in mdp.states:
U1[s] = R(s) + gamma * max([sum([p * U[s1] for (p, s1) in T(s, a)])
for a in mdp.actions(s)])
delta = max(delta, abs(U1[s] - U[s]))
if delta < epsilon * (1 - gamma) / gamma:
return U
|
def value_iteration(mdp, epsilon=0.001):
"Solving an MDP by value iteration. [Fig. 17.4]"
U1 = dict([(s, 0) for s in mdp.states])
R, T, gamma = mdp.R, mdp.T, mdp.gamma
while True:
U = U1.copy()
delta = 0
for s in mdp.states:
U1[s] = R(s) + gamma * max([sum([p * U[s1] for (p, s1) in T(s, a)])
for a in mdp.actions(s)])
delta = max(delta, abs(U1[s] - U[s]))
if delta < epsilon * (1 - gamma) / gamma:
return U
|
[
"Solving",
"an",
"MDP",
"by",
"value",
"iteration",
".",
"[",
"Fig",
".",
"17",
".",
"4",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/mdp.py#L90-L102
|
[
"def",
"value_iteration",
"(",
"mdp",
",",
"epsilon",
"=",
"0.001",
")",
":",
"U1",
"=",
"dict",
"(",
"[",
"(",
"s",
",",
"0",
")",
"for",
"s",
"in",
"mdp",
".",
"states",
"]",
")",
"R",
",",
"T",
",",
"gamma",
"=",
"mdp",
".",
"R",
",",
"mdp",
".",
"T",
",",
"mdp",
".",
"gamma",
"while",
"True",
":",
"U",
"=",
"U1",
".",
"copy",
"(",
")",
"delta",
"=",
"0",
"for",
"s",
"in",
"mdp",
".",
"states",
":",
"U1",
"[",
"s",
"]",
"=",
"R",
"(",
"s",
")",
"+",
"gamma",
"*",
"max",
"(",
"[",
"sum",
"(",
"[",
"p",
"*",
"U",
"[",
"s1",
"]",
"for",
"(",
"p",
",",
"s1",
")",
"in",
"T",
"(",
"s",
",",
"a",
")",
"]",
")",
"for",
"a",
"in",
"mdp",
".",
"actions",
"(",
"s",
")",
"]",
")",
"delta",
"=",
"max",
"(",
"delta",
",",
"abs",
"(",
"U1",
"[",
"s",
"]",
"-",
"U",
"[",
"s",
"]",
")",
")",
"if",
"delta",
"<",
"epsilon",
"*",
"(",
"1",
"-",
"gamma",
")",
"/",
"gamma",
":",
"return",
"U"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
best_policy
|
Given an MDP and a utility function U, determine the best policy,
as a mapping from state to action. (Equation 17.4)
|
aima/mdp.py
|
def best_policy(mdp, U):
"""Given an MDP and a utility function U, determine the best policy,
as a mapping from state to action. (Equation 17.4)"""
pi = {}
for s in mdp.states:
pi[s] = argmax(mdp.actions(s), lambda a:expected_utility(a, s, U, mdp))
return pi
|
def best_policy(mdp, U):
"""Given an MDP and a utility function U, determine the best policy,
as a mapping from state to action. (Equation 17.4)"""
pi = {}
for s in mdp.states:
pi[s] = argmax(mdp.actions(s), lambda a:expected_utility(a, s, U, mdp))
return pi
|
[
"Given",
"an",
"MDP",
"and",
"a",
"utility",
"function",
"U",
"determine",
"the",
"best",
"policy",
"as",
"a",
"mapping",
"from",
"state",
"to",
"action",
".",
"(",
"Equation",
"17",
".",
"4",
")"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/mdp.py#L104-L110
|
[
"def",
"best_policy",
"(",
"mdp",
",",
"U",
")",
":",
"pi",
"=",
"{",
"}",
"for",
"s",
"in",
"mdp",
".",
"states",
":",
"pi",
"[",
"s",
"]",
"=",
"argmax",
"(",
"mdp",
".",
"actions",
"(",
"s",
")",
",",
"lambda",
"a",
":",
"expected_utility",
"(",
"a",
",",
"s",
",",
"U",
",",
"mdp",
")",
")",
"return",
"pi"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
expected_utility
|
The expected utility of doing a in state s, according to the MDP and U.
|
aima/mdp.py
|
def expected_utility(a, s, U, mdp):
"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 expected_utility(a, s, U, mdp):
"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)])
|
[
"The",
"expected",
"utility",
"of",
"doing",
"a",
"in",
"state",
"s",
"according",
"to",
"the",
"MDP",
"and",
"U",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/mdp.py#L112-L114
|
[
"def",
"expected_utility",
"(",
"a",
",",
"s",
",",
"U",
",",
"mdp",
")",
":",
"return",
"sum",
"(",
"[",
"p",
"*",
"U",
"[",
"s1",
"]",
"for",
"(",
"p",
",",
"s1",
")",
"in",
"mdp",
".",
"T",
"(",
"s",
",",
"a",
")",
"]",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
policy_iteration
|
Solve an MDP by policy iteration [Fig. 17.7]
|
aima/mdp.py
|
def policy_iteration(mdp):
"Solve an MDP by policy iteration [Fig. 17.7]"
U = dict([(s, 0) for s in mdp.states])
pi = dict([(s, random.choice(mdp.actions(s))) for s in mdp.states])
while True:
U = policy_evaluation(pi, U, mdp)
unchanged = True
for s in mdp.states:
a = argmax(mdp.actions(s), lambda a: expected_utility(a,s,U,mdp))
if a != pi[s]:
pi[s] = a
unchanged = False
if unchanged:
return pi
|
def policy_iteration(mdp):
"Solve an MDP by policy iteration [Fig. 17.7]"
U = dict([(s, 0) for s in mdp.states])
pi = dict([(s, random.choice(mdp.actions(s))) for s in mdp.states])
while True:
U = policy_evaluation(pi, U, mdp)
unchanged = True
for s in mdp.states:
a = argmax(mdp.actions(s), lambda a: expected_utility(a,s,U,mdp))
if a != pi[s]:
pi[s] = a
unchanged = False
if unchanged:
return pi
|
[
"Solve",
"an",
"MDP",
"by",
"policy",
"iteration",
"[",
"Fig",
".",
"17",
".",
"7",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/mdp.py#L118-L131
|
[
"def",
"policy_iteration",
"(",
"mdp",
")",
":",
"U",
"=",
"dict",
"(",
"[",
"(",
"s",
",",
"0",
")",
"for",
"s",
"in",
"mdp",
".",
"states",
"]",
")",
"pi",
"=",
"dict",
"(",
"[",
"(",
"s",
",",
"random",
".",
"choice",
"(",
"mdp",
".",
"actions",
"(",
"s",
")",
")",
")",
"for",
"s",
"in",
"mdp",
".",
"states",
"]",
")",
"while",
"True",
":",
"U",
"=",
"policy_evaluation",
"(",
"pi",
",",
"U",
",",
"mdp",
")",
"unchanged",
"=",
"True",
"for",
"s",
"in",
"mdp",
".",
"states",
":",
"a",
"=",
"argmax",
"(",
"mdp",
".",
"actions",
"(",
"s",
")",
",",
"lambda",
"a",
":",
"expected_utility",
"(",
"a",
",",
"s",
",",
"U",
",",
"mdp",
")",
")",
"if",
"a",
"!=",
"pi",
"[",
"s",
"]",
":",
"pi",
"[",
"s",
"]",
"=",
"a",
"unchanged",
"=",
"False",
"if",
"unchanged",
":",
"return",
"pi"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
policy_evaluation
|
Return an updated utility mapping U from each state in the MDP to its
utility, using an approximation (modified policy iteration).
|
aima/mdp.py
|
def policy_evaluation(pi, U, mdp, k=20):
"""Return an updated utility mapping U from each state in the MDP to its
utility, using an approximation (modified policy iteration)."""
R, T, gamma = mdp.R, mdp.T, mdp.gamma
for i in range(k):
for s in mdp.states:
U[s] = R(s) + gamma * sum([p * U[s1] for (p, s1) in T(s, pi[s])])
return U
|
def policy_evaluation(pi, U, mdp, k=20):
"""Return an updated utility mapping U from each state in the MDP to its
utility, using an approximation (modified policy iteration)."""
R, T, gamma = mdp.R, mdp.T, mdp.gamma
for i in range(k):
for s in mdp.states:
U[s] = R(s) + gamma * sum([p * U[s1] for (p, s1) in T(s, pi[s])])
return U
|
[
"Return",
"an",
"updated",
"utility",
"mapping",
"U",
"from",
"each",
"state",
"in",
"the",
"MDP",
"to",
"its",
"utility",
"using",
"an",
"approximation",
"(",
"modified",
"policy",
"iteration",
")",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/mdp.py#L133-L140
|
[
"def",
"policy_evaluation",
"(",
"pi",
",",
"U",
",",
"mdp",
",",
"k",
"=",
"20",
")",
":",
"R",
",",
"T",
",",
"gamma",
"=",
"mdp",
".",
"R",
",",
"mdp",
".",
"T",
",",
"mdp",
".",
"gamma",
"for",
"i",
"in",
"range",
"(",
"k",
")",
":",
"for",
"s",
"in",
"mdp",
".",
"states",
":",
"U",
"[",
"s",
"]",
"=",
"R",
"(",
"s",
")",
"+",
"gamma",
"*",
"sum",
"(",
"[",
"p",
"*",
"U",
"[",
"s1",
"]",
"for",
"(",
"p",
",",
"s1",
")",
"in",
"T",
"(",
"s",
",",
"pi",
"[",
"s",
"]",
")",
"]",
")",
"return",
"U"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
GridMDP.go
|
Return the state that results from going in this direction.
|
aima/mdp.py
|
def go(self, state, direction):
"Return the state that results from going in this direction."
state1 = vector_add(state, direction)
return if_(state1 in self.states, state1, state)
|
def go(self, state, direction):
"Return the state that results from going in this direction."
state1 = vector_add(state, direction)
return if_(state1 in self.states, state1, state)
|
[
"Return",
"the",
"state",
"that",
"results",
"from",
"going",
"in",
"this",
"direction",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/mdp.py#L66-L69
|
[
"def",
"go",
"(",
"self",
",",
"state",
",",
"direction",
")",
":",
"state1",
"=",
"vector_add",
"(",
"state",
",",
"direction",
")",
"return",
"if_",
"(",
"state1",
"in",
"self",
".",
"states",
",",
"state1",
",",
"state",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
GridMDP.to_grid
|
Convert a mapping from (x, y) to v into a [[..., v, ...]] grid.
|
aima/mdp.py
|
def to_grid(self, mapping):
"""Convert a mapping from (x, y) to v into a [[..., v, ...]] grid."""
return list(reversed([[mapping.get((x,y), None)
for x in range(self.cols)]
for y in range(self.rows)]))
|
def to_grid(self, mapping):
"""Convert a mapping from (x, y) to v into a [[..., v, ...]] grid."""
return list(reversed([[mapping.get((x,y), None)
for x in range(self.cols)]
for y in range(self.rows)]))
|
[
"Convert",
"a",
"mapping",
"from",
"(",
"x",
"y",
")",
"to",
"v",
"into",
"a",
"[[",
"...",
"v",
"...",
"]]",
"grid",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/mdp.py#L71-L75
|
[
"def",
"to_grid",
"(",
"self",
",",
"mapping",
")",
":",
"return",
"list",
"(",
"reversed",
"(",
"[",
"[",
"mapping",
".",
"get",
"(",
"(",
"x",
",",
"y",
")",
",",
"None",
")",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"cols",
")",
"]",
"for",
"y",
"in",
"range",
"(",
"self",
".",
"rows",
")",
"]",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
SettingQuerySet.as_dict
|
Returns a ``SettingDict`` object for this queryset.
|
model_settings/models.py
|
def as_dict(self, default=None):
"""
Returns a ``SettingDict`` object for this queryset.
"""
settings = SettingDict(queryset=self, default=default)
return settings
|
def as_dict(self, default=None):
"""
Returns a ``SettingDict`` object for this queryset.
"""
settings = SettingDict(queryset=self, default=default)
return settings
|
[
"Returns",
"a",
"SettingDict",
"object",
"for",
"this",
"queryset",
"."
] |
ixc/django-model-settings
|
python
|
https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/models.py#L25-L30
|
[
"def",
"as_dict",
"(",
"self",
",",
"default",
"=",
"None",
")",
":",
"settings",
"=",
"SettingDict",
"(",
"queryset",
"=",
"self",
",",
"default",
"=",
"default",
")",
"return",
"settings"
] |
654233bf7f13619e4531741f9158e7034eac031b
|
valid
|
SettingQuerySet.create
|
Creates and returns an object of the appropriate type for ``value``.
|
model_settings/models.py
|
def create(self, name, value):
"""
Creates and returns an object of the appropriate type for ``value``.
"""
if value is None:
raise ValueError('Setting value cannot be `None`.')
model = Setting.get_model_for_value(value)
# Call `create()` method on the super class to avoid recursion.
obj = super(SettingQuerySet, model.objects.all()) \
.create(name=name, value=value)
return obj
|
def create(self, name, value):
"""
Creates and returns an object of the appropriate type for ``value``.
"""
if value is None:
raise ValueError('Setting value cannot be `None`.')
model = Setting.get_model_for_value(value)
# Call `create()` method on the super class to avoid recursion.
obj = super(SettingQuerySet, model.objects.all()) \
.create(name=name, value=value)
return obj
|
[
"Creates",
"and",
"returns",
"an",
"object",
"of",
"the",
"appropriate",
"type",
"for",
"value",
"."
] |
ixc/django-model-settings
|
python
|
https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/models.py#L32-L42
|
[
"def",
"create",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Setting value cannot be `None`.'",
")",
"model",
"=",
"Setting",
".",
"get_model_for_value",
"(",
"value",
")",
"# Call `create()` method on the super class to avoid recursion.",
"obj",
"=",
"super",
"(",
"SettingQuerySet",
",",
"model",
".",
"objects",
".",
"all",
"(",
")",
")",
".",
"create",
"(",
"name",
"=",
"name",
",",
"value",
"=",
"value",
")",
"return",
"obj"
] |
654233bf7f13619e4531741f9158e7034eac031b
|
valid
|
SettingModel.get_model_for_value
|
Iterates through setting value subclasses, returning one that is
compatible with the type of ``value``. Calls ``is_compatible()`` on
each subclass.
|
model_settings/models.py
|
def get_model_for_value(cls, value):
"""
Iterates through setting value subclasses, returning one that is
compatible with the type of ``value``. Calls ``is_compatible()`` on
each subclass.
"""
for related_object in get_all_related_objects(cls._meta):
model = getattr(related_object, 'related_model', related_object.model)
if issubclass(model, cls):
if model.is_compatible(value):
return model
raise ValueError(
'No compatible `SettingValueModel` subclass for %r' % value)
|
def get_model_for_value(cls, value):
"""
Iterates through setting value subclasses, returning one that is
compatible with the type of ``value``. Calls ``is_compatible()`` on
each subclass.
"""
for related_object in get_all_related_objects(cls._meta):
model = getattr(related_object, 'related_model', related_object.model)
if issubclass(model, cls):
if model.is_compatible(value):
return model
raise ValueError(
'No compatible `SettingValueModel` subclass for %r' % value)
|
[
"Iterates",
"through",
"setting",
"value",
"subclasses",
"returning",
"one",
"that",
"is",
"compatible",
"with",
"the",
"type",
"of",
"value",
".",
"Calls",
"is_compatible",
"()",
"on",
"each",
"subclass",
"."
] |
ixc/django-model-settings
|
python
|
https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/models.py#L67-L79
|
[
"def",
"get_model_for_value",
"(",
"cls",
",",
"value",
")",
":",
"for",
"related_object",
"in",
"get_all_related_objects",
"(",
"cls",
".",
"_meta",
")",
":",
"model",
"=",
"getattr",
"(",
"related_object",
",",
"'related_model'",
",",
"related_object",
".",
"model",
")",
"if",
"issubclass",
"(",
"model",
",",
"cls",
")",
":",
"if",
"model",
".",
"is_compatible",
"(",
"value",
")",
":",
"return",
"model",
"raise",
"ValueError",
"(",
"'No compatible `SettingValueModel` subclass for %r'",
"%",
"value",
")"
] |
654233bf7f13619e4531741f9158e7034eac031b
|
valid
|
SettingValueModel.is_compatible
|
Returns ``True`` if this model should be used to store ``value``.
Checks if ``value`` is an instance of ``value_type``. Override this
method if you need more advanced behaviour. For example, to distinguish
between single and multi-line text.
|
model_settings/models.py
|
def is_compatible(cls, value):
"""
Returns ``True`` if this model should be used to store ``value``.
Checks if ``value`` is an instance of ``value_type``. Override this
method if you need more advanced behaviour. For example, to distinguish
between single and multi-line text.
"""
if not hasattr(cls, 'value_type'):
raise NotImplementedError(
'You must define a `value_type` attribute or override the '
'`is_compatible()` method on `SettingValueModel` subclasses.')
return isinstance(value, cls.value_type)
|
def is_compatible(cls, value):
"""
Returns ``True`` if this model should be used to store ``value``.
Checks if ``value`` is an instance of ``value_type``. Override this
method if you need more advanced behaviour. For example, to distinguish
between single and multi-line text.
"""
if not hasattr(cls, 'value_type'):
raise NotImplementedError(
'You must define a `value_type` attribute or override the '
'`is_compatible()` method on `SettingValueModel` subclasses.')
return isinstance(value, cls.value_type)
|
[
"Returns",
"True",
"if",
"this",
"model",
"should",
"be",
"used",
"to",
"store",
"value",
"."
] |
ixc/django-model-settings
|
python
|
https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/models.py#L97-L109
|
[
"def",
"is_compatible",
"(",
"cls",
",",
"value",
")",
":",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"'value_type'",
")",
":",
"raise",
"NotImplementedError",
"(",
"'You must define a `value_type` attribute or override the '",
"'`is_compatible()` method on `SettingValueModel` subclasses.'",
")",
"return",
"isinstance",
"(",
"value",
",",
"cls",
".",
"value_type",
")"
] |
654233bf7f13619e4531741f9158e7034eac031b
|
valid
|
tree_search
|
Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
Don't worry about repeated paths to a state. [Fig. 3.7]
|
aima/search.py
|
def tree_search(problem, frontier):
"""Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
Don't worry about repeated paths to a state. [Fig. 3.7]"""
frontier.append(Node(problem.initial))
while frontier:
node = frontier.pop()
if problem.goal_test(node.state):
return node
frontier.extend(node.expand(problem))
return None
|
def tree_search(problem, frontier):
"""Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
Don't worry about repeated paths to a state. [Fig. 3.7]"""
frontier.append(Node(problem.initial))
while frontier:
node = frontier.pop()
if problem.goal_test(node.state):
return node
frontier.extend(node.expand(problem))
return None
|
[
"Search",
"through",
"the",
"successors",
"of",
"a",
"problem",
"to",
"find",
"a",
"goal",
".",
"The",
"argument",
"frontier",
"should",
"be",
"an",
"empty",
"queue",
".",
"Don",
"t",
"worry",
"about",
"repeated",
"paths",
"to",
"a",
"state",
".",
"[",
"Fig",
".",
"3",
".",
"7",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L151-L161
|
[
"def",
"tree_search",
"(",
"problem",
",",
"frontier",
")",
":",
"frontier",
".",
"append",
"(",
"Node",
"(",
"problem",
".",
"initial",
")",
")",
"while",
"frontier",
":",
"node",
"=",
"frontier",
".",
"pop",
"(",
")",
"if",
"problem",
".",
"goal_test",
"(",
"node",
".",
"state",
")",
":",
"return",
"node",
"frontier",
".",
"extend",
"(",
"node",
".",
"expand",
"(",
"problem",
")",
")",
"return",
"None"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
graph_search
|
Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
If two paths reach a state, only use the first one. [Fig. 3.7]
|
aima/search.py
|
def graph_search(problem, frontier):
"""Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
If two paths reach a state, only use the first one. [Fig. 3.7]"""
frontier.append(Node(problem.initial))
explored = set()
while frontier:
node = frontier.pop()
if problem.goal_test(node.state):
return node
explored.add(node.state)
frontier.extend(child for child in node.expand(problem)
if child.state not in explored
and child not in frontier)
return None
|
def graph_search(problem, frontier):
"""Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
If two paths reach a state, only use the first one. [Fig. 3.7]"""
frontier.append(Node(problem.initial))
explored = set()
while frontier:
node = frontier.pop()
if problem.goal_test(node.state):
return node
explored.add(node.state)
frontier.extend(child for child in node.expand(problem)
if child.state not in explored
and child not in frontier)
return None
|
[
"Search",
"through",
"the",
"successors",
"of",
"a",
"problem",
"to",
"find",
"a",
"goal",
".",
"The",
"argument",
"frontier",
"should",
"be",
"an",
"empty",
"queue",
".",
"If",
"two",
"paths",
"reach",
"a",
"state",
"only",
"use",
"the",
"first",
"one",
".",
"[",
"Fig",
".",
"3",
".",
"7",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L163-L177
|
[
"def",
"graph_search",
"(",
"problem",
",",
"frontier",
")",
":",
"frontier",
".",
"append",
"(",
"Node",
"(",
"problem",
".",
"initial",
")",
")",
"explored",
"=",
"set",
"(",
")",
"while",
"frontier",
":",
"node",
"=",
"frontier",
".",
"pop",
"(",
")",
"if",
"problem",
".",
"goal_test",
"(",
"node",
".",
"state",
")",
":",
"return",
"node",
"explored",
".",
"add",
"(",
"node",
".",
"state",
")",
"frontier",
".",
"extend",
"(",
"child",
"for",
"child",
"in",
"node",
".",
"expand",
"(",
"problem",
")",
"if",
"child",
".",
"state",
"not",
"in",
"explored",
"and",
"child",
"not",
"in",
"frontier",
")",
"return",
"None"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
breadth_first_search
|
[Fig. 3.11]
|
aima/search.py
|
def breadth_first_search(problem):
"[Fig. 3.11]"
node = Node(problem.initial)
if problem.goal_test(node.state):
return node
frontier = FIFOQueue()
frontier.append(node)
explored = set()
while frontier:
node = frontier.pop()
explored.add(node.state)
for child in node.expand(problem):
if child.state not in explored and child not in frontier:
if problem.goal_test(child.state):
return child
frontier.append(child)
return None
|
def breadth_first_search(problem):
"[Fig. 3.11]"
node = Node(problem.initial)
if problem.goal_test(node.state):
return node
frontier = FIFOQueue()
frontier.append(node)
explored = set()
while frontier:
node = frontier.pop()
explored.add(node.state)
for child in node.expand(problem):
if child.state not in explored and child not in frontier:
if problem.goal_test(child.state):
return child
frontier.append(child)
return None
|
[
"[",
"Fig",
".",
"3",
".",
"11",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L191-L207
|
[
"def",
"breadth_first_search",
"(",
"problem",
")",
":",
"node",
"=",
"Node",
"(",
"problem",
".",
"initial",
")",
"if",
"problem",
".",
"goal_test",
"(",
"node",
".",
"state",
")",
":",
"return",
"node",
"frontier",
"=",
"FIFOQueue",
"(",
")",
"frontier",
".",
"append",
"(",
"node",
")",
"explored",
"=",
"set",
"(",
")",
"while",
"frontier",
":",
"node",
"=",
"frontier",
".",
"pop",
"(",
")",
"explored",
".",
"add",
"(",
"node",
".",
"state",
")",
"for",
"child",
"in",
"node",
".",
"expand",
"(",
"problem",
")",
":",
"if",
"child",
".",
"state",
"not",
"in",
"explored",
"and",
"child",
"not",
"in",
"frontier",
":",
"if",
"problem",
".",
"goal_test",
"(",
"child",
".",
"state",
")",
":",
"return",
"child",
"frontier",
".",
"append",
"(",
"child",
")",
"return",
"None"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
best_first_graph_search
|
Search the nodes with the lowest f scores first.
You specify the function f(node) that you want to minimize; for example,
if f is a heuristic estimate to the goal, then we have greedy best
first search; if f is node.depth then we have breadth-first search.
There is a subtlety: the line "f = memoize(f, 'f')" means that the f
values will be cached on the nodes as they are computed. So after doing
a best first search you can examine the f values of the path returned.
|
aima/search.py
|
def best_first_graph_search(problem, f):
"""Search the nodes with the lowest f scores first.
You specify the function f(node) that you want to minimize; for example,
if f is a heuristic estimate to the goal, then we have greedy best
first search; if f is node.depth then we have breadth-first search.
There is a subtlety: the line "f = memoize(f, 'f')" means that the f
values will be cached on the nodes as they are computed. So after doing
a best first search you can examine the f values of the path returned."""
f = memoize(f, 'f')
node = Node(problem.initial)
if problem.goal_test(node.state):
return node
frontier = PriorityQueue(min, f)
frontier.append(node)
explored = set()
while frontier:
node = frontier.pop()
if problem.goal_test(node.state):
return node
explored.add(node.state)
for child in node.expand(problem):
if child.state not in explored and child not in frontier:
frontier.append(child)
elif child in frontier:
incumbent = frontier[child]
if f(child) < f(incumbent):
del frontier[incumbent]
frontier.append(child)
return None
|
def best_first_graph_search(problem, f):
"""Search the nodes with the lowest f scores first.
You specify the function f(node) that you want to minimize; for example,
if f is a heuristic estimate to the goal, then we have greedy best
first search; if f is node.depth then we have breadth-first search.
There is a subtlety: the line "f = memoize(f, 'f')" means that the f
values will be cached on the nodes as they are computed. So after doing
a best first search you can examine the f values of the path returned."""
f = memoize(f, 'f')
node = Node(problem.initial)
if problem.goal_test(node.state):
return node
frontier = PriorityQueue(min, f)
frontier.append(node)
explored = set()
while frontier:
node = frontier.pop()
if problem.goal_test(node.state):
return node
explored.add(node.state)
for child in node.expand(problem):
if child.state not in explored and child not in frontier:
frontier.append(child)
elif child in frontier:
incumbent = frontier[child]
if f(child) < f(incumbent):
del frontier[incumbent]
frontier.append(child)
return None
|
[
"Search",
"the",
"nodes",
"with",
"the",
"lowest",
"f",
"scores",
"first",
".",
"You",
"specify",
"the",
"function",
"f",
"(",
"node",
")",
"that",
"you",
"want",
"to",
"minimize",
";",
"for",
"example",
"if",
"f",
"is",
"a",
"heuristic",
"estimate",
"to",
"the",
"goal",
"then",
"we",
"have",
"greedy",
"best",
"first",
"search",
";",
"if",
"f",
"is",
"node",
".",
"depth",
"then",
"we",
"have",
"breadth",
"-",
"first",
"search",
".",
"There",
"is",
"a",
"subtlety",
":",
"the",
"line",
"f",
"=",
"memoize",
"(",
"f",
"f",
")",
"means",
"that",
"the",
"f",
"values",
"will",
"be",
"cached",
"on",
"the",
"nodes",
"as",
"they",
"are",
"computed",
".",
"So",
"after",
"doing",
"a",
"best",
"first",
"search",
"you",
"can",
"examine",
"the",
"f",
"values",
"of",
"the",
"path",
"returned",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L209-L237
|
[
"def",
"best_first_graph_search",
"(",
"problem",
",",
"f",
")",
":",
"f",
"=",
"memoize",
"(",
"f",
",",
"'f'",
")",
"node",
"=",
"Node",
"(",
"problem",
".",
"initial",
")",
"if",
"problem",
".",
"goal_test",
"(",
"node",
".",
"state",
")",
":",
"return",
"node",
"frontier",
"=",
"PriorityQueue",
"(",
"min",
",",
"f",
")",
"frontier",
".",
"append",
"(",
"node",
")",
"explored",
"=",
"set",
"(",
")",
"while",
"frontier",
":",
"node",
"=",
"frontier",
".",
"pop",
"(",
")",
"if",
"problem",
".",
"goal_test",
"(",
"node",
".",
"state",
")",
":",
"return",
"node",
"explored",
".",
"add",
"(",
"node",
".",
"state",
")",
"for",
"child",
"in",
"node",
".",
"expand",
"(",
"problem",
")",
":",
"if",
"child",
".",
"state",
"not",
"in",
"explored",
"and",
"child",
"not",
"in",
"frontier",
":",
"frontier",
".",
"append",
"(",
"child",
")",
"elif",
"child",
"in",
"frontier",
":",
"incumbent",
"=",
"frontier",
"[",
"child",
"]",
"if",
"f",
"(",
"child",
")",
"<",
"f",
"(",
"incumbent",
")",
":",
"del",
"frontier",
"[",
"incumbent",
"]",
"frontier",
".",
"append",
"(",
"child",
")",
"return",
"None"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
depth_limited_search
|
[Fig. 3.17]
|
aima/search.py
|
def depth_limited_search(problem, limit=50):
"[Fig. 3.17]"
def recursive_dls(node, problem, limit):
if problem.goal_test(node.state):
return node
elif node.depth == limit:
return 'cutoff'
else:
cutoff_occurred = False
for child in node.expand(problem):
result = recursive_dls(child, problem, limit)
if result == 'cutoff':
cutoff_occurred = True
elif result is not None:
return result
return if_(cutoff_occurred, 'cutoff', None)
# Body of depth_limited_search:
return recursive_dls(Node(problem.initial), problem, limit)
|
def depth_limited_search(problem, limit=50):
"[Fig. 3.17]"
def recursive_dls(node, problem, limit):
if problem.goal_test(node.state):
return node
elif node.depth == limit:
return 'cutoff'
else:
cutoff_occurred = False
for child in node.expand(problem):
result = recursive_dls(child, problem, limit)
if result == 'cutoff':
cutoff_occurred = True
elif result is not None:
return result
return if_(cutoff_occurred, 'cutoff', None)
# Body of depth_limited_search:
return recursive_dls(Node(problem.initial), problem, limit)
|
[
"[",
"Fig",
".",
"3",
".",
"17",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L243-L261
|
[
"def",
"depth_limited_search",
"(",
"problem",
",",
"limit",
"=",
"50",
")",
":",
"def",
"recursive_dls",
"(",
"node",
",",
"problem",
",",
"limit",
")",
":",
"if",
"problem",
".",
"goal_test",
"(",
"node",
".",
"state",
")",
":",
"return",
"node",
"elif",
"node",
".",
"depth",
"==",
"limit",
":",
"return",
"'cutoff'",
"else",
":",
"cutoff_occurred",
"=",
"False",
"for",
"child",
"in",
"node",
".",
"expand",
"(",
"problem",
")",
":",
"result",
"=",
"recursive_dls",
"(",
"child",
",",
"problem",
",",
"limit",
")",
"if",
"result",
"==",
"'cutoff'",
":",
"cutoff_occurred",
"=",
"True",
"elif",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"return",
"if_",
"(",
"cutoff_occurred",
",",
"'cutoff'",
",",
"None",
")",
"# Body of depth_limited_search:",
"return",
"recursive_dls",
"(",
"Node",
"(",
"problem",
".",
"initial",
")",
",",
"problem",
",",
"limit",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
iterative_deepening_search
|
[Fig. 3.18]
|
aima/search.py
|
def iterative_deepening_search(problem):
"[Fig. 3.18]"
for depth in xrange(sys.maxint):
result = depth_limited_search(problem, depth)
if result != 'cutoff':
return result
|
def iterative_deepening_search(problem):
"[Fig. 3.18]"
for depth in xrange(sys.maxint):
result = depth_limited_search(problem, depth)
if result != 'cutoff':
return result
|
[
"[",
"Fig",
".",
"3",
".",
"18",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L263-L268
|
[
"def",
"iterative_deepening_search",
"(",
"problem",
")",
":",
"for",
"depth",
"in",
"xrange",
"(",
"sys",
".",
"maxint",
")",
":",
"result",
"=",
"depth_limited_search",
"(",
"problem",
",",
"depth",
")",
"if",
"result",
"!=",
"'cutoff'",
":",
"return",
"result"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
astar_search
|
A* search is best-first graph search with f(n) = g(n)+h(n).
You need to specify the h function when you call astar_search, or
else in your Problem subclass.
|
aima/search.py
|
def astar_search(problem, h=None):
"""A* search is best-first graph search with f(n) = g(n)+h(n).
You need to specify the h function when you call astar_search, or
else in your Problem subclass."""
h = memoize(h or problem.h, 'h')
return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
|
def astar_search(problem, h=None):
"""A* search is best-first graph search with f(n) = g(n)+h(n).
You need to specify the h function when you call astar_search, or
else in your Problem subclass."""
h = memoize(h or problem.h, 'h')
return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
|
[
"A",
"*",
"search",
"is",
"best",
"-",
"first",
"graph",
"search",
"with",
"f",
"(",
"n",
")",
"=",
"g",
"(",
"n",
")",
"+",
"h",
"(",
"n",
")",
".",
"You",
"need",
"to",
"specify",
"the",
"h",
"function",
"when",
"you",
"call",
"astar_search",
"or",
"else",
"in",
"your",
"Problem",
"subclass",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L276-L281
|
[
"def",
"astar_search",
"(",
"problem",
",",
"h",
"=",
"None",
")",
":",
"h",
"=",
"memoize",
"(",
"h",
"or",
"problem",
".",
"h",
",",
"'h'",
")",
"return",
"best_first_graph_search",
"(",
"problem",
",",
"lambda",
"n",
":",
"n",
".",
"path_cost",
"+",
"h",
"(",
"n",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
recursive_best_first_search
|
[Fig. 3.26]
|
aima/search.py
|
def recursive_best_first_search(problem, h=None):
"[Fig. 3.26]"
h = memoize(h or problem.h, 'h')
def RBFS(problem, node, flimit):
if problem.goal_test(node.state):
return node, 0 # (The second value is immaterial)
successors = node.expand(problem)
if len(successors) == 0:
return None, infinity
for s in successors:
s.f = max(s.path_cost + h(s), node.f)
while True:
successors.sort(lambda x,y: cmp(x.f, y.f)) # Order by lowest f value
best = successors[0]
if best.f > flimit:
return None, best.f
if len(successors) > 1:
alternative = successors[1].f
else:
alternative = infinity
result, best.f = RBFS(problem, best, min(flimit, alternative))
if result is not None:
return result, best.f
node = Node(problem.initial)
node.f = h(node)
result, bestf = RBFS(problem, node, infinity)
return result
|
def recursive_best_first_search(problem, h=None):
"[Fig. 3.26]"
h = memoize(h or problem.h, 'h')
def RBFS(problem, node, flimit):
if problem.goal_test(node.state):
return node, 0 # (The second value is immaterial)
successors = node.expand(problem)
if len(successors) == 0:
return None, infinity
for s in successors:
s.f = max(s.path_cost + h(s), node.f)
while True:
successors.sort(lambda x,y: cmp(x.f, y.f)) # Order by lowest f value
best = successors[0]
if best.f > flimit:
return None, best.f
if len(successors) > 1:
alternative = successors[1].f
else:
alternative = infinity
result, best.f = RBFS(problem, best, min(flimit, alternative))
if result is not None:
return result, best.f
node = Node(problem.initial)
node.f = h(node)
result, bestf = RBFS(problem, node, infinity)
return result
|
[
"[",
"Fig",
".",
"3",
".",
"26",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L286-L314
|
[
"def",
"recursive_best_first_search",
"(",
"problem",
",",
"h",
"=",
"None",
")",
":",
"h",
"=",
"memoize",
"(",
"h",
"or",
"problem",
".",
"h",
",",
"'h'",
")",
"def",
"RBFS",
"(",
"problem",
",",
"node",
",",
"flimit",
")",
":",
"if",
"problem",
".",
"goal_test",
"(",
"node",
".",
"state",
")",
":",
"return",
"node",
",",
"0",
"# (The second value is immaterial)",
"successors",
"=",
"node",
".",
"expand",
"(",
"problem",
")",
"if",
"len",
"(",
"successors",
")",
"==",
"0",
":",
"return",
"None",
",",
"infinity",
"for",
"s",
"in",
"successors",
":",
"s",
".",
"f",
"=",
"max",
"(",
"s",
".",
"path_cost",
"+",
"h",
"(",
"s",
")",
",",
"node",
".",
"f",
")",
"while",
"True",
":",
"successors",
".",
"sort",
"(",
"lambda",
"x",
",",
"y",
":",
"cmp",
"(",
"x",
".",
"f",
",",
"y",
".",
"f",
")",
")",
"# Order by lowest f value",
"best",
"=",
"successors",
"[",
"0",
"]",
"if",
"best",
".",
"f",
">",
"flimit",
":",
"return",
"None",
",",
"best",
".",
"f",
"if",
"len",
"(",
"successors",
")",
">",
"1",
":",
"alternative",
"=",
"successors",
"[",
"1",
"]",
".",
"f",
"else",
":",
"alternative",
"=",
"infinity",
"result",
",",
"best",
".",
"f",
"=",
"RBFS",
"(",
"problem",
",",
"best",
",",
"min",
"(",
"flimit",
",",
"alternative",
")",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
",",
"best",
".",
"f",
"node",
"=",
"Node",
"(",
"problem",
".",
"initial",
")",
"node",
".",
"f",
"=",
"h",
"(",
"node",
")",
"result",
",",
"bestf",
"=",
"RBFS",
"(",
"problem",
",",
"node",
",",
"infinity",
")",
"return",
"result"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
hill_climbing
|
From the initial node, keep choosing the neighbor with highest value,
stopping when no neighbor is better. [Fig. 4.2]
|
aima/search.py
|
def hill_climbing(problem):
"""From the initial node, keep choosing the neighbor with highest value,
stopping when no neighbor is better. [Fig. 4.2]"""
current = Node(problem.initial)
while True:
neighbors = current.expand(problem)
if not neighbors:
break
neighbor = argmax_random_tie(neighbors,
lambda node: problem.value(node.state))
if problem.value(neighbor.state) <= problem.value(current.state):
break
current = neighbor
return current.state
|
def hill_climbing(problem):
"""From the initial node, keep choosing the neighbor with highest value,
stopping when no neighbor is better. [Fig. 4.2]"""
current = Node(problem.initial)
while True:
neighbors = current.expand(problem)
if not neighbors:
break
neighbor = argmax_random_tie(neighbors,
lambda node: problem.value(node.state))
if problem.value(neighbor.state) <= problem.value(current.state):
break
current = neighbor
return current.state
|
[
"From",
"the",
"initial",
"node",
"keep",
"choosing",
"the",
"neighbor",
"with",
"highest",
"value",
"stopping",
"when",
"no",
"neighbor",
"is",
"better",
".",
"[",
"Fig",
".",
"4",
".",
"2",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L316-L329
|
[
"def",
"hill_climbing",
"(",
"problem",
")",
":",
"current",
"=",
"Node",
"(",
"problem",
".",
"initial",
")",
"while",
"True",
":",
"neighbors",
"=",
"current",
".",
"expand",
"(",
"problem",
")",
"if",
"not",
"neighbors",
":",
"break",
"neighbor",
"=",
"argmax_random_tie",
"(",
"neighbors",
",",
"lambda",
"node",
":",
"problem",
".",
"value",
"(",
"node",
".",
"state",
")",
")",
"if",
"problem",
".",
"value",
"(",
"neighbor",
".",
"state",
")",
"<=",
"problem",
".",
"value",
"(",
"current",
".",
"state",
")",
":",
"break",
"current",
"=",
"neighbor",
"return",
"current",
".",
"state"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
exp_schedule
|
One possible schedule function for simulated annealing
|
aima/search.py
|
def exp_schedule(k=20, lam=0.005, limit=100):
"One possible schedule function for simulated annealing"
return lambda t: if_(t < limit, k * math.exp(-lam * t), 0)
|
def exp_schedule(k=20, lam=0.005, limit=100):
"One possible schedule function for simulated annealing"
return lambda t: if_(t < limit, k * math.exp(-lam * t), 0)
|
[
"One",
"possible",
"schedule",
"function",
"for",
"simulated",
"annealing"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L331-L333
|
[
"def",
"exp_schedule",
"(",
"k",
"=",
"20",
",",
"lam",
"=",
"0.005",
",",
"limit",
"=",
"100",
")",
":",
"return",
"lambda",
"t",
":",
"if_",
"(",
"t",
"<",
"limit",
",",
"k",
"*",
"math",
".",
"exp",
"(",
"-",
"lam",
"*",
"t",
")",
",",
"0",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
simulated_annealing
|
[Fig. 4.5]
|
aima/search.py
|
def simulated_annealing(problem, schedule=exp_schedule()):
"[Fig. 4.5]"
current = Node(problem.initial)
for t in xrange(sys.maxint):
T = schedule(t)
if T == 0:
return current
neighbors = current.expand(problem)
if not neighbors:
return current
next = random.choice(neighbors)
delta_e = problem.value(next.state) - problem.value(current.state)
if delta_e > 0 or probability(math.exp(delta_e/T)):
current = next
|
def simulated_annealing(problem, schedule=exp_schedule()):
"[Fig. 4.5]"
current = Node(problem.initial)
for t in xrange(sys.maxint):
T = schedule(t)
if T == 0:
return current
neighbors = current.expand(problem)
if not neighbors:
return current
next = random.choice(neighbors)
delta_e = problem.value(next.state) - problem.value(current.state)
if delta_e > 0 or probability(math.exp(delta_e/T)):
current = next
|
[
"[",
"Fig",
".",
"4",
".",
"5",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L335-L348
|
[
"def",
"simulated_annealing",
"(",
"problem",
",",
"schedule",
"=",
"exp_schedule",
"(",
")",
")",
":",
"current",
"=",
"Node",
"(",
"problem",
".",
"initial",
")",
"for",
"t",
"in",
"xrange",
"(",
"sys",
".",
"maxint",
")",
":",
"T",
"=",
"schedule",
"(",
"t",
")",
"if",
"T",
"==",
"0",
":",
"return",
"current",
"neighbors",
"=",
"current",
".",
"expand",
"(",
"problem",
")",
"if",
"not",
"neighbors",
":",
"return",
"current",
"next",
"=",
"random",
".",
"choice",
"(",
"neighbors",
")",
"delta_e",
"=",
"problem",
".",
"value",
"(",
"next",
".",
"state",
")",
"-",
"problem",
".",
"value",
"(",
"current",
".",
"state",
")",
"if",
"delta_e",
">",
"0",
"or",
"probability",
"(",
"math",
".",
"exp",
"(",
"delta_e",
"/",
"T",
")",
")",
":",
"current",
"=",
"next"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
genetic_search
|
Call genetic_algorithm on the appropriate parts of a problem.
This requires the problem to have states that can mate and mutate,
plus a value method that scores states.
|
aima/search.py
|
def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20):
"""Call genetic_algorithm on the appropriate parts of a problem.
This requires the problem to have states that can mate and mutate,
plus a value method that scores states."""
s = problem.initial_state
states = [problem.result(s, a) for a in problem.actions(s)]
random.shuffle(states)
return genetic_algorithm(states[:n], problem.value, ngen, pmut)
|
def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20):
"""Call genetic_algorithm on the appropriate parts of a problem.
This requires the problem to have states that can mate and mutate,
plus a value method that scores states."""
s = problem.initial_state
states = [problem.result(s, a) for a in problem.actions(s)]
random.shuffle(states)
return genetic_algorithm(states[:n], problem.value, ngen, pmut)
|
[
"Call",
"genetic_algorithm",
"on",
"the",
"appropriate",
"parts",
"of",
"a",
"problem",
".",
"This",
"requires",
"the",
"problem",
"to",
"have",
"states",
"that",
"can",
"mate",
"and",
"mutate",
"plus",
"a",
"value",
"method",
"that",
"scores",
"states",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L365-L372
|
[
"def",
"genetic_search",
"(",
"problem",
",",
"fitness_fn",
",",
"ngen",
"=",
"1000",
",",
"pmut",
"=",
"0.1",
",",
"n",
"=",
"20",
")",
":",
"s",
"=",
"problem",
".",
"initial_state",
"states",
"=",
"[",
"problem",
".",
"result",
"(",
"s",
",",
"a",
")",
"for",
"a",
"in",
"problem",
".",
"actions",
"(",
"s",
")",
"]",
"random",
".",
"shuffle",
"(",
"states",
")",
"return",
"genetic_algorithm",
"(",
"states",
"[",
":",
"n",
"]",
",",
"problem",
".",
"value",
",",
"ngen",
",",
"pmut",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
genetic_algorithm
|
[Fig. 4.8]
|
aima/search.py
|
def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.1):
"[Fig. 4.8]"
for i in range(ngen):
new_population = []
for i in len(population):
fitnesses = map(fitness_fn, population)
p1, p2 = weighted_sample_with_replacement(population, fitnesses, 2)
child = p1.mate(p2)
if random.uniform(0, 1) < pmut:
child.mutate()
new_population.append(child)
population = new_population
return argmax(population, fitness_fn)
|
def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.1):
"[Fig. 4.8]"
for i in range(ngen):
new_population = []
for i in len(population):
fitnesses = map(fitness_fn, population)
p1, p2 = weighted_sample_with_replacement(population, fitnesses, 2)
child = p1.mate(p2)
if random.uniform(0, 1) < pmut:
child.mutate()
new_population.append(child)
population = new_population
return argmax(population, fitness_fn)
|
[
"[",
"Fig",
".",
"4",
".",
"8",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L374-L386
|
[
"def",
"genetic_algorithm",
"(",
"population",
",",
"fitness_fn",
",",
"ngen",
"=",
"1000",
",",
"pmut",
"=",
"0.1",
")",
":",
"for",
"i",
"in",
"range",
"(",
"ngen",
")",
":",
"new_population",
"=",
"[",
"]",
"for",
"i",
"in",
"len",
"(",
"population",
")",
":",
"fitnesses",
"=",
"map",
"(",
"fitness_fn",
",",
"population",
")",
"p1",
",",
"p2",
"=",
"weighted_sample_with_replacement",
"(",
"population",
",",
"fitnesses",
",",
"2",
")",
"child",
"=",
"p1",
".",
"mate",
"(",
"p2",
")",
"if",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
")",
"<",
"pmut",
":",
"child",
".",
"mutate",
"(",
")",
"new_population",
".",
"append",
"(",
"child",
")",
"population",
"=",
"new_population",
"return",
"argmax",
"(",
"population",
",",
"fitness_fn",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
RandomGraph
|
Construct a random graph, with the specified nodes, and random links.
The nodes are laid out randomly on a (width x height) rectangle.
Then each node is connected to the min_links nearest neighbors.
Because inverse links are added, some nodes will have more connections.
The distance between nodes is the hypotenuse times curvature(),
where curvature() defaults to a random number between 1.1 and 1.5.
|
aima/search.py
|
def RandomGraph(nodes=range(10), min_links=2, width=400, height=300,
curvature=lambda: random.uniform(1.1, 1.5)):
"""Construct a random graph, with the specified nodes, and random links.
The nodes are laid out randomly on a (width x height) rectangle.
Then each node is connected to the min_links nearest neighbors.
Because inverse links are added, some nodes will have more connections.
The distance between nodes is the hypotenuse times curvature(),
where curvature() defaults to a random number between 1.1 and 1.5."""
g = UndirectedGraph()
g.locations = {}
## Build the cities
for node in nodes:
g.locations[node] = (random.randrange(width), random.randrange(height))
## Build roads from each city to at least min_links nearest neighbors.
for i in range(min_links):
for node in nodes:
if len(g.get(node)) < min_links:
here = g.locations[node]
def distance_to_node(n):
if n is node or g.get(node,n): return infinity
return distance(g.locations[n], here)
neighbor = argmin(nodes, distance_to_node)
d = distance(g.locations[neighbor], here) * curvature()
g.connect(node, neighbor, int(d))
return g
|
def RandomGraph(nodes=range(10), min_links=2, width=400, height=300,
curvature=lambda: random.uniform(1.1, 1.5)):
"""Construct a random graph, with the specified nodes, and random links.
The nodes are laid out randomly on a (width x height) rectangle.
Then each node is connected to the min_links nearest neighbors.
Because inverse links are added, some nodes will have more connections.
The distance between nodes is the hypotenuse times curvature(),
where curvature() defaults to a random number between 1.1 and 1.5."""
g = UndirectedGraph()
g.locations = {}
## Build the cities
for node in nodes:
g.locations[node] = (random.randrange(width), random.randrange(height))
## Build roads from each city to at least min_links nearest neighbors.
for i in range(min_links):
for node in nodes:
if len(g.get(node)) < min_links:
here = g.locations[node]
def distance_to_node(n):
if n is node or g.get(node,n): return infinity
return distance(g.locations[n], here)
neighbor = argmin(nodes, distance_to_node)
d = distance(g.locations[neighbor], here) * curvature()
g.connect(node, neighbor, int(d))
return g
|
[
"Construct",
"a",
"random",
"graph",
"with",
"the",
"specified",
"nodes",
"and",
"random",
"links",
".",
"The",
"nodes",
"are",
"laid",
"out",
"randomly",
"on",
"a",
"(",
"width",
"x",
"height",
")",
"rectangle",
".",
"Then",
"each",
"node",
"is",
"connected",
"to",
"the",
"min_links",
"nearest",
"neighbors",
".",
"Because",
"inverse",
"links",
"are",
"added",
"some",
"nodes",
"will",
"have",
"more",
"connections",
".",
"The",
"distance",
"between",
"nodes",
"is",
"the",
"hypotenuse",
"times",
"curvature",
"()",
"where",
"curvature",
"()",
"defaults",
"to",
"a",
"random",
"number",
"between",
"1",
".",
"1",
"and",
"1",
".",
"5",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L459-L483
|
[
"def",
"RandomGraph",
"(",
"nodes",
"=",
"range",
"(",
"10",
")",
",",
"min_links",
"=",
"2",
",",
"width",
"=",
"400",
",",
"height",
"=",
"300",
",",
"curvature",
"=",
"lambda",
":",
"random",
".",
"uniform",
"(",
"1.1",
",",
"1.5",
")",
")",
":",
"g",
"=",
"UndirectedGraph",
"(",
")",
"g",
".",
"locations",
"=",
"{",
"}",
"## Build the cities",
"for",
"node",
"in",
"nodes",
":",
"g",
".",
"locations",
"[",
"node",
"]",
"=",
"(",
"random",
".",
"randrange",
"(",
"width",
")",
",",
"random",
".",
"randrange",
"(",
"height",
")",
")",
"## Build roads from each city to at least min_links nearest neighbors.",
"for",
"i",
"in",
"range",
"(",
"min_links",
")",
":",
"for",
"node",
"in",
"nodes",
":",
"if",
"len",
"(",
"g",
".",
"get",
"(",
"node",
")",
")",
"<",
"min_links",
":",
"here",
"=",
"g",
".",
"locations",
"[",
"node",
"]",
"def",
"distance_to_node",
"(",
"n",
")",
":",
"if",
"n",
"is",
"node",
"or",
"g",
".",
"get",
"(",
"node",
",",
"n",
")",
":",
"return",
"infinity",
"return",
"distance",
"(",
"g",
".",
"locations",
"[",
"n",
"]",
",",
"here",
")",
"neighbor",
"=",
"argmin",
"(",
"nodes",
",",
"distance_to_node",
")",
"d",
"=",
"distance",
"(",
"g",
".",
"locations",
"[",
"neighbor",
"]",
",",
"here",
")",
"*",
"curvature",
"(",
")",
"g",
".",
"connect",
"(",
"node",
",",
"neighbor",
",",
"int",
"(",
"d",
")",
")",
"return",
"g"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
random_boggle
|
Return a random Boggle board of size n x n.
We represent a board as a linear list of letters.
|
aima/search.py
|
def random_boggle(n=4):
"""Return a random Boggle board of size n x n.
We represent a board as a linear list of letters."""
cubes = [cubes16[i % 16] for i in range(n*n)]
random.shuffle(cubes)
return map(random.choice, cubes)
|
def random_boggle(n=4):
"""Return a random Boggle board of size n x n.
We represent a board as a linear list of letters."""
cubes = [cubes16[i % 16] for i in range(n*n)]
random.shuffle(cubes)
return map(random.choice, cubes)
|
[
"Return",
"a",
"random",
"Boggle",
"board",
"of",
"size",
"n",
"x",
"n",
".",
"We",
"represent",
"a",
"board",
"as",
"a",
"linear",
"list",
"of",
"letters",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L601-L606
|
[
"def",
"random_boggle",
"(",
"n",
"=",
"4",
")",
":",
"cubes",
"=",
"[",
"cubes16",
"[",
"i",
"%",
"16",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
"*",
"n",
")",
"]",
"random",
".",
"shuffle",
"(",
"cubes",
")",
"return",
"map",
"(",
"random",
".",
"choice",
",",
"cubes",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
print_boggle
|
Print the board in a 2-d array.
|
aima/search.py
|
def print_boggle(board):
"Print the board in a 2-d array."
n2 = len(board); n = exact_sqrt(n2)
for i in range(n2):
if i % n == 0 and i > 0: print
if board[i] == 'Q': print 'Qu',
else: print str(board[i]) + ' ',
print
|
def print_boggle(board):
"Print the board in a 2-d array."
n2 = len(board); n = exact_sqrt(n2)
for i in range(n2):
if i % n == 0 and i > 0: print
if board[i] == 'Q': print 'Qu',
else: print str(board[i]) + ' ',
print
|
[
"Print",
"the",
"board",
"in",
"a",
"2",
"-",
"d",
"array",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L613-L620
|
[
"def",
"print_boggle",
"(",
"board",
")",
":",
"n2",
"=",
"len",
"(",
"board",
")",
"n",
"=",
"exact_sqrt",
"(",
"n2",
")",
"for",
"i",
"in",
"range",
"(",
"n2",
")",
":",
"if",
"i",
"%",
"n",
"==",
"0",
"and",
"i",
">",
"0",
":",
"print",
"if",
"board",
"[",
"i",
"]",
"==",
"'Q'",
":",
"print",
"'Qu'",
",",
"else",
":",
"print",
"str",
"(",
"board",
"[",
"i",
"]",
")",
"+",
"' '",
",",
"print"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
boggle_neighbors
|
Return a list of lists, where the i-th element is the list of indexes
for the neighbors of square i.
|
aima/search.py
|
def boggle_neighbors(n2, cache={}):
"""Return a list of lists, where the i-th element is the list of indexes
for the neighbors of square i."""
if cache.get(n2):
return cache.get(n2)
n = exact_sqrt(n2)
neighbors = [None] * n2
for i in range(n2):
neighbors[i] = []
on_top = i < n
on_bottom = i >= n2 - n
on_left = i % n == 0
on_right = (i+1) % n == 0
if not on_top:
neighbors[i].append(i - n)
if not on_left: neighbors[i].append(i - n - 1)
if not on_right: neighbors[i].append(i - n + 1)
if not on_bottom:
neighbors[i].append(i + n)
if not on_left: neighbors[i].append(i + n - 1)
if not on_right: neighbors[i].append(i + n + 1)
if not on_left: neighbors[i].append(i - 1)
if not on_right: neighbors[i].append(i + 1)
cache[n2] = neighbors
return neighbors
|
def boggle_neighbors(n2, cache={}):
"""Return a list of lists, where the i-th element is the list of indexes
for the neighbors of square i."""
if cache.get(n2):
return cache.get(n2)
n = exact_sqrt(n2)
neighbors = [None] * n2
for i in range(n2):
neighbors[i] = []
on_top = i < n
on_bottom = i >= n2 - n
on_left = i % n == 0
on_right = (i+1) % n == 0
if not on_top:
neighbors[i].append(i - n)
if not on_left: neighbors[i].append(i - n - 1)
if not on_right: neighbors[i].append(i - n + 1)
if not on_bottom:
neighbors[i].append(i + n)
if not on_left: neighbors[i].append(i + n - 1)
if not on_right: neighbors[i].append(i + n + 1)
if not on_left: neighbors[i].append(i - 1)
if not on_right: neighbors[i].append(i + 1)
cache[n2] = neighbors
return neighbors
|
[
"Return",
"a",
"list",
"of",
"lists",
"where",
"the",
"i",
"-",
"th",
"element",
"is",
"the",
"list",
"of",
"indexes",
"for",
"the",
"neighbors",
"of",
"square",
"i",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L622-L646
|
[
"def",
"boggle_neighbors",
"(",
"n2",
",",
"cache",
"=",
"{",
"}",
")",
":",
"if",
"cache",
".",
"get",
"(",
"n2",
")",
":",
"return",
"cache",
".",
"get",
"(",
"n2",
")",
"n",
"=",
"exact_sqrt",
"(",
"n2",
")",
"neighbors",
"=",
"[",
"None",
"]",
"*",
"n2",
"for",
"i",
"in",
"range",
"(",
"n2",
")",
":",
"neighbors",
"[",
"i",
"]",
"=",
"[",
"]",
"on_top",
"=",
"i",
"<",
"n",
"on_bottom",
"=",
"i",
">=",
"n2",
"-",
"n",
"on_left",
"=",
"i",
"%",
"n",
"==",
"0",
"on_right",
"=",
"(",
"i",
"+",
"1",
")",
"%",
"n",
"==",
"0",
"if",
"not",
"on_top",
":",
"neighbors",
"[",
"i",
"]",
".",
"append",
"(",
"i",
"-",
"n",
")",
"if",
"not",
"on_left",
":",
"neighbors",
"[",
"i",
"]",
".",
"append",
"(",
"i",
"-",
"n",
"-",
"1",
")",
"if",
"not",
"on_right",
":",
"neighbors",
"[",
"i",
"]",
".",
"append",
"(",
"i",
"-",
"n",
"+",
"1",
")",
"if",
"not",
"on_bottom",
":",
"neighbors",
"[",
"i",
"]",
".",
"append",
"(",
"i",
"+",
"n",
")",
"if",
"not",
"on_left",
":",
"neighbors",
"[",
"i",
"]",
".",
"append",
"(",
"i",
"+",
"n",
"-",
"1",
")",
"if",
"not",
"on_right",
":",
"neighbors",
"[",
"i",
"]",
".",
"append",
"(",
"i",
"+",
"n",
"+",
"1",
")",
"if",
"not",
"on_left",
":",
"neighbors",
"[",
"i",
"]",
".",
"append",
"(",
"i",
"-",
"1",
")",
"if",
"not",
"on_right",
":",
"neighbors",
"[",
"i",
"]",
".",
"append",
"(",
"i",
"+",
"1",
")",
"cache",
"[",
"n2",
"]",
"=",
"neighbors",
"return",
"neighbors"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
exact_sqrt
|
If n2 is a perfect square, return its square root, else raise error.
|
aima/search.py
|
def exact_sqrt(n2):
"If n2 is a perfect square, return its square root, else raise error."
n = int(math.sqrt(n2))
assert n * n == n2
return n
|
def exact_sqrt(n2):
"If n2 is a perfect square, return its square root, else raise error."
n = int(math.sqrt(n2))
assert n * n == n2
return n
|
[
"If",
"n2",
"is",
"a",
"perfect",
"square",
"return",
"its",
"square",
"root",
"else",
"raise",
"error",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L648-L652
|
[
"def",
"exact_sqrt",
"(",
"n2",
")",
":",
"n",
"=",
"int",
"(",
"math",
".",
"sqrt",
"(",
"n2",
")",
")",
"assert",
"n",
"*",
"n",
"==",
"n2",
"return",
"n"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
boggle_hill_climbing
|
Solve inverse Boggle by hill-climbing: find a high-scoring board by
starting with a random one and changing it.
|
aima/search.py
|
def boggle_hill_climbing(board=None, ntimes=100, verbose=True):
"""Solve inverse Boggle by hill-climbing: find a high-scoring board by
starting with a random one and changing it."""
finder = BoggleFinder()
if board is None:
board = random_boggle()
best = len(finder.set_board(board))
for _ in range(ntimes):
i, oldc = mutate_boggle(board)
new = len(finder.set_board(board))
if new > best:
best = new
if verbose: print best, _, board
else:
board[i] = oldc ## Change back
if verbose:
print_boggle(board)
return board, best
|
def boggle_hill_climbing(board=None, ntimes=100, verbose=True):
"""Solve inverse Boggle by hill-climbing: find a high-scoring board by
starting with a random one and changing it."""
finder = BoggleFinder()
if board is None:
board = random_boggle()
best = len(finder.set_board(board))
for _ in range(ntimes):
i, oldc = mutate_boggle(board)
new = len(finder.set_board(board))
if new > best:
best = new
if verbose: print best, _, board
else:
board[i] = oldc ## Change back
if verbose:
print_boggle(board)
return board, best
|
[
"Solve",
"inverse",
"Boggle",
"by",
"hill",
"-",
"climbing",
":",
"find",
"a",
"high",
"-",
"scoring",
"board",
"by",
"starting",
"with",
"a",
"random",
"one",
"and",
"changing",
"it",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L749-L766
|
[
"def",
"boggle_hill_climbing",
"(",
"board",
"=",
"None",
",",
"ntimes",
"=",
"100",
",",
"verbose",
"=",
"True",
")",
":",
"finder",
"=",
"BoggleFinder",
"(",
")",
"if",
"board",
"is",
"None",
":",
"board",
"=",
"random_boggle",
"(",
")",
"best",
"=",
"len",
"(",
"finder",
".",
"set_board",
"(",
"board",
")",
")",
"for",
"_",
"in",
"range",
"(",
"ntimes",
")",
":",
"i",
",",
"oldc",
"=",
"mutate_boggle",
"(",
"board",
")",
"new",
"=",
"len",
"(",
"finder",
".",
"set_board",
"(",
"board",
")",
")",
"if",
"new",
">",
"best",
":",
"best",
"=",
"new",
"if",
"verbose",
":",
"print",
"best",
",",
"_",
",",
"board",
"else",
":",
"board",
"[",
"i",
"]",
"=",
"oldc",
"## Change back",
"if",
"verbose",
":",
"print_boggle",
"(",
"board",
")",
"return",
"board",
",",
"best"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
compare_graph_searchers
|
Prints a table of results like this:
>>> compare_graph_searchers()
Searcher Romania(A, B) Romania(O, N) Australia
breadth_first_tree_search < 21/ 22/ 59/B> <1158/1159/3288/N> < 7/ 8/ 22/WA>
breadth_first_search < 7/ 11/ 18/B> < 19/ 20/ 45/N> < 2/ 6/ 8/WA>
depth_first_graph_search < 8/ 9/ 20/B> < 16/ 17/ 38/N> < 4/ 5/ 11/WA>
iterative_deepening_search < 11/ 33/ 31/B> < 656/1815/1812/N> < 3/ 11/ 11/WA>
depth_limited_search < 54/ 65/ 185/B> < 387/1012/1125/N> < 50/ 54/ 200/WA>
recursive_best_first_search < 5/ 6/ 15/B> <5887/5888/16532/N> < 11/ 12/ 43/WA>
|
aima/search.py
|
def compare_graph_searchers():
"""Prints a table of results like this:
>>> compare_graph_searchers()
Searcher Romania(A, B) Romania(O, N) Australia
breadth_first_tree_search < 21/ 22/ 59/B> <1158/1159/3288/N> < 7/ 8/ 22/WA>
breadth_first_search < 7/ 11/ 18/B> < 19/ 20/ 45/N> < 2/ 6/ 8/WA>
depth_first_graph_search < 8/ 9/ 20/B> < 16/ 17/ 38/N> < 4/ 5/ 11/WA>
iterative_deepening_search < 11/ 33/ 31/B> < 656/1815/1812/N> < 3/ 11/ 11/WA>
depth_limited_search < 54/ 65/ 185/B> < 387/1012/1125/N> < 50/ 54/ 200/WA>
recursive_best_first_search < 5/ 6/ 15/B> <5887/5888/16532/N> < 11/ 12/ 43/WA>"""
compare_searchers(problems=[GraphProblem('A', 'B', romania),
GraphProblem('O', 'N', romania),
GraphProblem('Q', 'WA', australia)],
header=['Searcher', 'Romania(A, B)', 'Romania(O, N)', 'Australia'])
|
def compare_graph_searchers():
"""Prints a table of results like this:
>>> compare_graph_searchers()
Searcher Romania(A, B) Romania(O, N) Australia
breadth_first_tree_search < 21/ 22/ 59/B> <1158/1159/3288/N> < 7/ 8/ 22/WA>
breadth_first_search < 7/ 11/ 18/B> < 19/ 20/ 45/N> < 2/ 6/ 8/WA>
depth_first_graph_search < 8/ 9/ 20/B> < 16/ 17/ 38/N> < 4/ 5/ 11/WA>
iterative_deepening_search < 11/ 33/ 31/B> < 656/1815/1812/N> < 3/ 11/ 11/WA>
depth_limited_search < 54/ 65/ 185/B> < 387/1012/1125/N> < 50/ 54/ 200/WA>
recursive_best_first_search < 5/ 6/ 15/B> <5887/5888/16532/N> < 11/ 12/ 43/WA>"""
compare_searchers(problems=[GraphProblem('A', 'B', romania),
GraphProblem('O', 'N', romania),
GraphProblem('Q', 'WA', australia)],
header=['Searcher', 'Romania(A, B)', 'Romania(O, N)', 'Australia'])
|
[
"Prints",
"a",
"table",
"of",
"results",
"like",
"this",
":",
">>>",
"compare_graph_searchers",
"()",
"Searcher",
"Romania",
"(",
"A",
"B",
")",
"Romania",
"(",
"O",
"N",
")",
"Australia",
"breadth_first_tree_search",
"<",
"21",
"/",
"22",
"/",
"59",
"/",
"B",
">",
"<1158",
"/",
"1159",
"/",
"3288",
"/",
"N",
">",
"<",
"7",
"/",
"8",
"/",
"22",
"/",
"WA",
">",
"breadth_first_search",
"<",
"7",
"/",
"11",
"/",
"18",
"/",
"B",
">",
"<",
"19",
"/",
"20",
"/",
"45",
"/",
"N",
">",
"<",
"2",
"/",
"6",
"/",
"8",
"/",
"WA",
">",
"depth_first_graph_search",
"<",
"8",
"/",
"9",
"/",
"20",
"/",
"B",
">",
"<",
"16",
"/",
"17",
"/",
"38",
"/",
"N",
">",
"<",
"4",
"/",
"5",
"/",
"11",
"/",
"WA",
">",
"iterative_deepening_search",
"<",
"11",
"/",
"33",
"/",
"31",
"/",
"B",
">",
"<",
"656",
"/",
"1815",
"/",
"1812",
"/",
"N",
">",
"<",
"3",
"/",
"11",
"/",
"11",
"/",
"WA",
">",
"depth_limited_search",
"<",
"54",
"/",
"65",
"/",
"185",
"/",
"B",
">",
"<",
"387",
"/",
"1012",
"/",
"1125",
"/",
"N",
">",
"<",
"50",
"/",
"54",
"/",
"200",
"/",
"WA",
">",
"recursive_best_first_search",
"<",
"5",
"/",
"6",
"/",
"15",
"/",
"B",
">",
"<5887",
"/",
"5888",
"/",
"16532",
"/",
"N",
">",
"<",
"11",
"/",
"12",
"/",
"43",
"/",
"WA",
">"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L835-L848
|
[
"def",
"compare_graph_searchers",
"(",
")",
":",
"compare_searchers",
"(",
"problems",
"=",
"[",
"GraphProblem",
"(",
"'A'",
",",
"'B'",
",",
"romania",
")",
",",
"GraphProblem",
"(",
"'O'",
",",
"'N'",
",",
"romania",
")",
",",
"GraphProblem",
"(",
"'Q'",
",",
"'WA'",
",",
"australia",
")",
"]",
",",
"header",
"=",
"[",
"'Searcher'",
",",
"'Romania(A, B)'",
",",
"'Romania(O, N)'",
",",
"'Australia'",
"]",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Node.expand
|
List the nodes reachable in one step from this node.
|
aima/search.py
|
def expand(self, problem):
"List the nodes reachable in one step from this node."
return [self.child_node(problem, action)
for action in problem.actions(self.state)]
|
def expand(self, problem):
"List the nodes reachable in one step from this node."
return [self.child_node(problem, action)
for action in problem.actions(self.state)]
|
[
"List",
"the",
"nodes",
"reachable",
"in",
"one",
"step",
"from",
"this",
"node",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L86-L89
|
[
"def",
"expand",
"(",
"self",
",",
"problem",
")",
":",
"return",
"[",
"self",
".",
"child_node",
"(",
"problem",
",",
"action",
")",
"for",
"action",
"in",
"problem",
".",
"actions",
"(",
"self",
".",
"state",
")",
"]"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Node.child_node
|
Fig. 3.10
|
aima/search.py
|
def child_node(self, problem, action):
"Fig. 3.10"
next = problem.result(self.state, action)
return Node(next, self, action,
problem.path_cost(self.path_cost, self.state, action, next))
|
def child_node(self, problem, action):
"Fig. 3.10"
next = problem.result(self.state, action)
return Node(next, self, action,
problem.path_cost(self.path_cost, self.state, action, next))
|
[
"Fig",
".",
"3",
".",
"10"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L91-L95
|
[
"def",
"child_node",
"(",
"self",
",",
"problem",
",",
"action",
")",
":",
"next",
"=",
"problem",
".",
"result",
"(",
"self",
".",
"state",
",",
"action",
")",
"return",
"Node",
"(",
"next",
",",
"self",
",",
"action",
",",
"problem",
".",
"path_cost",
"(",
"self",
".",
"path_cost",
",",
"self",
".",
"state",
",",
"action",
",",
"next",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Node.path
|
Return a list of nodes forming the path from the root to this node.
|
aima/search.py
|
def path(self):
"Return a list of nodes forming the path from the root to this node."
node, path_back = self, []
while node:
path_back.append(node)
node = node.parent
return list(reversed(path_back))
|
def path(self):
"Return a list of nodes forming the path from the root to this node."
node, path_back = self, []
while node:
path_back.append(node)
node = node.parent
return list(reversed(path_back))
|
[
"Return",
"a",
"list",
"of",
"nodes",
"forming",
"the",
"path",
"from",
"the",
"root",
"to",
"this",
"node",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L101-L107
|
[
"def",
"path",
"(",
"self",
")",
":",
"node",
",",
"path_back",
"=",
"self",
",",
"[",
"]",
"while",
"node",
":",
"path_back",
".",
"append",
"(",
"node",
")",
"node",
"=",
"node",
".",
"parent",
"return",
"list",
"(",
"reversed",
"(",
"path_back",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
GAState.mate
|
Return a new individual crossing self and other.
|
aima/search.py
|
def mate(self, other):
"Return a new individual crossing self and other."
c = random.randrange(len(self.genes))
return self.__class__(self.genes[:c] + other.genes[c:])
|
def mate(self, other):
"Return a new individual crossing self and other."
c = random.randrange(len(self.genes))
return self.__class__(self.genes[:c] + other.genes[c:])
|
[
"Return",
"a",
"new",
"individual",
"crossing",
"self",
"and",
"other",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L393-L396
|
[
"def",
"mate",
"(",
"self",
",",
"other",
")",
":",
"c",
"=",
"random",
".",
"randrange",
"(",
"len",
"(",
"self",
".",
"genes",
")",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"genes",
"[",
":",
"c",
"]",
"+",
"other",
".",
"genes",
"[",
"c",
":",
"]",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Graph.make_undirected
|
Make a digraph into an undirected graph by adding symmetric edges.
|
aima/search.py
|
def make_undirected(self):
"Make a digraph into an undirected graph by adding symmetric edges."
for a in self.dict.keys():
for (b, distance) in self.dict[a].items():
self.connect1(b, a, distance)
|
def make_undirected(self):
"Make a digraph into an undirected graph by adding symmetric edges."
for a in self.dict.keys():
for (b, distance) in self.dict[a].items():
self.connect1(b, a, distance)
|
[
"Make",
"a",
"digraph",
"into",
"an",
"undirected",
"graph",
"by",
"adding",
"symmetric",
"edges",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L427-L431
|
[
"def",
"make_undirected",
"(",
"self",
")",
":",
"for",
"a",
"in",
"self",
".",
"dict",
".",
"keys",
"(",
")",
":",
"for",
"(",
"b",
",",
"distance",
")",
"in",
"self",
".",
"dict",
"[",
"a",
"]",
".",
"items",
"(",
")",
":",
"self",
".",
"connect1",
"(",
"b",
",",
"a",
",",
"distance",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Graph.connect
|
Add a link from A and B of given distance, and also add the inverse
link if the graph is undirected.
|
aima/search.py
|
def connect(self, A, B, distance=1):
"""Add a link from A and B of given distance, and also add the inverse
link if the graph is undirected."""
self.connect1(A, B, distance)
if not self.directed: self.connect1(B, A, distance)
|
def connect(self, A, B, distance=1):
"""Add a link from A and B of given distance, and also add the inverse
link if the graph is undirected."""
self.connect1(A, B, distance)
if not self.directed: self.connect1(B, A, distance)
|
[
"Add",
"a",
"link",
"from",
"A",
"and",
"B",
"of",
"given",
"distance",
"and",
"also",
"add",
"the",
"inverse",
"link",
"if",
"the",
"graph",
"is",
"undirected",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L433-L437
|
[
"def",
"connect",
"(",
"self",
",",
"A",
",",
"B",
",",
"distance",
"=",
"1",
")",
":",
"self",
".",
"connect1",
"(",
"A",
",",
"B",
",",
"distance",
")",
"if",
"not",
"self",
".",
"directed",
":",
"self",
".",
"connect1",
"(",
"B",
",",
"A",
",",
"distance",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Graph.connect1
|
Add a link from A to B of given distance, in one direction only.
|
aima/search.py
|
def connect1(self, A, B, distance):
"Add a link from A to B of given distance, in one direction only."
self.dict.setdefault(A,{})[B] = distance
|
def connect1(self, A, B, distance):
"Add a link from A to B of given distance, in one direction only."
self.dict.setdefault(A,{})[B] = distance
|
[
"Add",
"a",
"link",
"from",
"A",
"to",
"B",
"of",
"given",
"distance",
"in",
"one",
"direction",
"only",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L439-L441
|
[
"def",
"connect1",
"(",
"self",
",",
"A",
",",
"B",
",",
"distance",
")",
":",
"self",
".",
"dict",
".",
"setdefault",
"(",
"A",
",",
"{",
"}",
")",
"[",
"B",
"]",
"=",
"distance"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Graph.get
|
Return a link distance or a dict of {node: distance} entries.
.get(a,b) returns the distance or None;
.get(a) returns a dict of {node: distance} entries, possibly {}.
|
aima/search.py
|
def get(self, a, b=None):
"""Return a link distance or a dict of {node: distance} entries.
.get(a,b) returns the distance or None;
.get(a) returns a dict of {node: distance} entries, possibly {}."""
links = self.dict.setdefault(a, {})
if b is None: return links
else: return links.get(b)
|
def get(self, a, b=None):
"""Return a link distance or a dict of {node: distance} entries.
.get(a,b) returns the distance or None;
.get(a) returns a dict of {node: distance} entries, possibly {}."""
links = self.dict.setdefault(a, {})
if b is None: return links
else: return links.get(b)
|
[
"Return",
"a",
"link",
"distance",
"or",
"a",
"dict",
"of",
"{",
"node",
":",
"distance",
"}",
"entries",
".",
".",
"get",
"(",
"a",
"b",
")",
"returns",
"the",
"distance",
"or",
"None",
";",
".",
"get",
"(",
"a",
")",
"returns",
"a",
"dict",
"of",
"{",
"node",
":",
"distance",
"}",
"entries",
"possibly",
"{}",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L443-L449
|
[
"def",
"get",
"(",
"self",
",",
"a",
",",
"b",
"=",
"None",
")",
":",
"links",
"=",
"self",
".",
"dict",
".",
"setdefault",
"(",
"a",
",",
"{",
"}",
")",
"if",
"b",
"is",
"None",
":",
"return",
"links",
"else",
":",
"return",
"links",
".",
"get",
"(",
"b",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
GraphProblem.h
|
h function is straight-line distance from a node's state to goal.
|
aima/search.py
|
def h(self, node):
"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]))
else:
return infinity
|
def h(self, node):
"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]))
else:
return infinity
|
[
"h",
"function",
"is",
"straight",
"-",
"line",
"distance",
"from",
"a",
"node",
"s",
"state",
"to",
"goal",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L532-L538
|
[
"def",
"h",
"(",
"self",
",",
"node",
")",
":",
"locs",
"=",
"getattr",
"(",
"self",
".",
"graph",
",",
"'locations'",
",",
"None",
")",
"if",
"locs",
":",
"return",
"int",
"(",
"distance",
"(",
"locs",
"[",
"node",
".",
"state",
"]",
",",
"locs",
"[",
"self",
".",
"goal",
"]",
")",
")",
"else",
":",
"return",
"infinity"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NQueensProblem.actions
|
In the leftmost empty column, try all non-conflicting rows.
|
aima/search.py
|
def actions(self, state):
"In the leftmost empty column, try all non-conflicting rows."
if state[-1] is not None:
return [] # All columns filled; no successors
else:
col = state.index(None)
return [row for row in range(self.N)
if not self.conflicted(state, row, col)]
|
def actions(self, state):
"In the leftmost empty column, try all non-conflicting rows."
if state[-1] is not None:
return [] # All columns filled; no successors
else:
col = state.index(None)
return [row for row in range(self.N)
if not self.conflicted(state, row, col)]
|
[
"In",
"the",
"leftmost",
"empty",
"column",
"try",
"all",
"non",
"-",
"conflicting",
"rows",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L555-L562
|
[
"def",
"actions",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
"[",
"-",
"1",
"]",
"is",
"not",
"None",
":",
"return",
"[",
"]",
"# All columns filled; no successors",
"else",
":",
"col",
"=",
"state",
".",
"index",
"(",
"None",
")",
"return",
"[",
"row",
"for",
"row",
"in",
"range",
"(",
"self",
".",
"N",
")",
"if",
"not",
"self",
".",
"conflicted",
"(",
"state",
",",
"row",
",",
"col",
")",
"]"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NQueensProblem.result
|
Place the next queen at the given row.
|
aima/search.py
|
def result(self, state, row):
"Place the next queen at the given row."
col = state.index(None)
new = state[:]
new[col] = row
return new
|
def result(self, state, row):
"Place the next queen at the given row."
col = state.index(None)
new = state[:]
new[col] = row
return new
|
[
"Place",
"the",
"next",
"queen",
"at",
"the",
"given",
"row",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L564-L569
|
[
"def",
"result",
"(",
"self",
",",
"state",
",",
"row",
")",
":",
"col",
"=",
"state",
".",
"index",
"(",
"None",
")",
"new",
"=",
"state",
"[",
":",
"]",
"new",
"[",
"col",
"]",
"=",
"row",
"return",
"new"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NQueensProblem.conflicted
|
Would placing a queen at (row, col) conflict with anything?
|
aima/search.py
|
def conflicted(self, state, row, col):
"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 conflicted(self, state, row, col):
"Would placing a queen at (row, col) conflict with anything?"
return any(self.conflict(row, col, state[c], c)
for c in range(col))
|
[
"Would",
"placing",
"a",
"queen",
"at",
"(",
"row",
"col",
")",
"conflict",
"with",
"anything?"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L571-L574
|
[
"def",
"conflicted",
"(",
"self",
",",
"state",
",",
"row",
",",
"col",
")",
":",
"return",
"any",
"(",
"self",
".",
"conflict",
"(",
"row",
",",
"col",
",",
"state",
"[",
"c",
"]",
",",
"c",
")",
"for",
"c",
"in",
"range",
"(",
"col",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
NQueensProblem.conflict
|
Would putting two queens in (row1, col1) and (row2, col2) conflict?
|
aima/search.py
|
def conflict(self, row1, col1, row2, col2):
"Would putting two queens in (row1, col1) and (row2, col2) conflict?"
return (row1 == row2 ## same row
or col1 == col2 ## same column
or row1-col1 == row2-col2 ## same \ diagonal
or row1+col1 == row2+col2)
|
def conflict(self, row1, col1, row2, col2):
"Would putting two queens in (row1, col1) and (row2, col2) conflict?"
return (row1 == row2 ## same row
or col1 == col2 ## same column
or row1-col1 == row2-col2 ## same \ diagonal
or row1+col1 == row2+col2)
|
[
"Would",
"putting",
"two",
"queens",
"in",
"(",
"row1",
"col1",
")",
"and",
"(",
"row2",
"col2",
")",
"conflict?"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L576-L581
|
[
"def",
"conflict",
"(",
"self",
",",
"row1",
",",
"col1",
",",
"row2",
",",
"col2",
")",
":",
"return",
"(",
"row1",
"==",
"row2",
"## same row",
"or",
"col1",
"==",
"col2",
"## same column",
"or",
"row1",
"-",
"col1",
"==",
"row2",
"-",
"col2",
"## same \\ diagonal",
"or",
"row1",
"+",
"col1",
"==",
"row2",
"+",
"col2",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Wordlist.lookup
|
See if prefix is in dictionary, as a full word or as a prefix.
Return two values: the first is the lowest i such that
words[i].startswith(prefix), or is None; the second is
True iff prefix itself is in the Wordlist.
|
aima/search.py
|
def lookup(self, prefix, lo=0, hi=None):
"""See if prefix is in dictionary, as a full word or as a prefix.
Return two values: the first is the lowest i such that
words[i].startswith(prefix), or is None; the second is
True iff prefix itself is in the Wordlist."""
words = self.words
if hi is None: hi = len(words)
i = bisect.bisect_left(words, prefix, lo, hi)
if i < len(words) and words[i].startswith(prefix):
return i, (words[i] == prefix)
else:
return None, False
|
def lookup(self, prefix, lo=0, hi=None):
"""See if prefix is in dictionary, as a full word or as a prefix.
Return two values: the first is the lowest i such that
words[i].startswith(prefix), or is None; the second is
True iff prefix itself is in the Wordlist."""
words = self.words
if hi is None: hi = len(words)
i = bisect.bisect_left(words, prefix, lo, hi)
if i < len(words) and words[i].startswith(prefix):
return i, (words[i] == prefix)
else:
return None, False
|
[
"See",
"if",
"prefix",
"is",
"in",
"dictionary",
"as",
"a",
"full",
"word",
"or",
"as",
"a",
"prefix",
".",
"Return",
"two",
"values",
":",
"the",
"first",
"is",
"the",
"lowest",
"i",
"such",
"that",
"words",
"[",
"i",
"]",
".",
"startswith",
"(",
"prefix",
")",
"or",
"is",
"None",
";",
"the",
"second",
"is",
"True",
"iff",
"prefix",
"itself",
"is",
"in",
"the",
"Wordlist",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L670-L681
|
[
"def",
"lookup",
"(",
"self",
",",
"prefix",
",",
"lo",
"=",
"0",
",",
"hi",
"=",
"None",
")",
":",
"words",
"=",
"self",
".",
"words",
"if",
"hi",
"is",
"None",
":",
"hi",
"=",
"len",
"(",
"words",
")",
"i",
"=",
"bisect",
".",
"bisect_left",
"(",
"words",
",",
"prefix",
",",
"lo",
",",
"hi",
")",
"if",
"i",
"<",
"len",
"(",
"words",
")",
"and",
"words",
"[",
"i",
"]",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"i",
",",
"(",
"words",
"[",
"i",
"]",
"==",
"prefix",
")",
"else",
":",
"return",
"None",
",",
"False"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
BoggleFinder.set_board
|
Set the board, and find all the words in it.
|
aima/search.py
|
def set_board(self, board=None):
"Set the board, and find all the words in it."
if board is None:
board = random_boggle()
self.board = board
self.neighbors = boggle_neighbors(len(board))
self.found = {}
for i in range(len(board)):
lo, hi = self.wordlist.bounds[board[i]]
self.find(lo, hi, i, [], '')
return self
|
def set_board(self, board=None):
"Set the board, and find all the words in it."
if board is None:
board = random_boggle()
self.board = board
self.neighbors = boggle_neighbors(len(board))
self.found = {}
for i in range(len(board)):
lo, hi = self.wordlist.bounds[board[i]]
self.find(lo, hi, i, [], '')
return self
|
[
"Set",
"the",
"board",
"and",
"find",
"all",
"the",
"words",
"in",
"it",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L703-L713
|
[
"def",
"set_board",
"(",
"self",
",",
"board",
"=",
"None",
")",
":",
"if",
"board",
"is",
"None",
":",
"board",
"=",
"random_boggle",
"(",
")",
"self",
".",
"board",
"=",
"board",
"self",
".",
"neighbors",
"=",
"boggle_neighbors",
"(",
"len",
"(",
"board",
")",
")",
"self",
".",
"found",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"board",
")",
")",
":",
"lo",
",",
"hi",
"=",
"self",
".",
"wordlist",
".",
"bounds",
"[",
"board",
"[",
"i",
"]",
"]",
"self",
".",
"find",
"(",
"lo",
",",
"hi",
",",
"i",
",",
"[",
"]",
",",
"''",
")",
"return",
"self"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
BoggleFinder.find
|
Looking in square i, find the words that continue the prefix,
considering the entries in self.wordlist.words[lo:hi], and not
revisiting the squares in visited.
|
aima/search.py
|
def find(self, lo, hi, i, visited, prefix):
"""Looking in square i, find the words that continue the prefix,
considering the entries in self.wordlist.words[lo:hi], and not
revisiting the squares in visited."""
if i in visited:
return
wordpos, is_word = self.wordlist.lookup(prefix, lo, hi)
if wordpos is not None:
if is_word:
self.found[prefix] = True
visited.append(i)
c = self.board[i]
if c == 'Q': c = 'QU'
prefix += c
for j in self.neighbors[i]:
self.find(wordpos, hi, j, visited, prefix)
visited.pop()
|
def find(self, lo, hi, i, visited, prefix):
"""Looking in square i, find the words that continue the prefix,
considering the entries in self.wordlist.words[lo:hi], and not
revisiting the squares in visited."""
if i in visited:
return
wordpos, is_word = self.wordlist.lookup(prefix, lo, hi)
if wordpos is not None:
if is_word:
self.found[prefix] = True
visited.append(i)
c = self.board[i]
if c == 'Q': c = 'QU'
prefix += c
for j in self.neighbors[i]:
self.find(wordpos, hi, j, visited, prefix)
visited.pop()
|
[
"Looking",
"in",
"square",
"i",
"find",
"the",
"words",
"that",
"continue",
"the",
"prefix",
"considering",
"the",
"entries",
"in",
"self",
".",
"wordlist",
".",
"words",
"[",
"lo",
":",
"hi",
"]",
"and",
"not",
"revisiting",
"the",
"squares",
"in",
"visited",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L715-L731
|
[
"def",
"find",
"(",
"self",
",",
"lo",
",",
"hi",
",",
"i",
",",
"visited",
",",
"prefix",
")",
":",
"if",
"i",
"in",
"visited",
":",
"return",
"wordpos",
",",
"is_word",
"=",
"self",
".",
"wordlist",
".",
"lookup",
"(",
"prefix",
",",
"lo",
",",
"hi",
")",
"if",
"wordpos",
"is",
"not",
"None",
":",
"if",
"is_word",
":",
"self",
".",
"found",
"[",
"prefix",
"]",
"=",
"True",
"visited",
".",
"append",
"(",
"i",
")",
"c",
"=",
"self",
".",
"board",
"[",
"i",
"]",
"if",
"c",
"==",
"'Q'",
":",
"c",
"=",
"'QU'",
"prefix",
"+=",
"c",
"for",
"j",
"in",
"self",
".",
"neighbors",
"[",
"i",
"]",
":",
"self",
".",
"find",
"(",
"wordpos",
",",
"hi",
",",
"j",
",",
"visited",
",",
"prefix",
")",
"visited",
".",
"pop",
"(",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
BoggleFinder.score
|
The total score for the words found, according to the rules.
|
aima/search.py
|
def score(self):
"The total score for the words found, according to the rules."
return sum([self.scores[len(w)] for w in self.words()])
|
def score(self):
"The total score for the words found, according to the rules."
return sum([self.scores[len(w)] for w in self.words()])
|
[
"The",
"total",
"score",
"for",
"the",
"words",
"found",
"according",
"to",
"the",
"rules",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L739-L741
|
[
"def",
"score",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"[",
"self",
".",
"scores",
"[",
"len",
"(",
"w",
")",
"]",
"for",
"w",
"in",
"self",
".",
"words",
"(",
")",
"]",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
TraceAgent
|
Wrap the agent's program to print its input and output. This will let
you see what the agent is doing in the environment.
|
aima/agents.py
|
def TraceAgent(agent):
"""Wrap the agent's program to print its input and output. This will let
you see what the agent is doing in the environment."""
old_program = agent.program
def new_program(percept):
action = old_program(percept)
print '%s perceives %s and does %s' % (agent, percept, action)
return action
agent.program = new_program
return agent
|
def TraceAgent(agent):
"""Wrap the agent's program to print its input and output. This will let
you see what the agent is doing in the environment."""
old_program = agent.program
def new_program(percept):
action = old_program(percept)
print '%s perceives %s and does %s' % (agent, percept, action)
return action
agent.program = new_program
return agent
|
[
"Wrap",
"the",
"agent",
"s",
"program",
"to",
"print",
"its",
"input",
"and",
"output",
".",
"This",
"will",
"let",
"you",
"see",
"what",
"the",
"agent",
"is",
"doing",
"in",
"the",
"environment",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L91-L100
|
[
"def",
"TraceAgent",
"(",
"agent",
")",
":",
"old_program",
"=",
"agent",
".",
"program",
"def",
"new_program",
"(",
"percept",
")",
":",
"action",
"=",
"old_program",
"(",
"percept",
")",
"print",
"'%s perceives %s and does %s'",
"%",
"(",
"agent",
",",
"percept",
",",
"action",
")",
"return",
"action",
"agent",
".",
"program",
"=",
"new_program",
"return",
"agent"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
TableDrivenAgentProgram
|
This agent selects an action based on the percept sequence.
It is practical only for tiny domains.
To customize it, provide as table a dictionary of all
{percept_sequence:action} pairs. [Fig. 2.7]
|
aima/agents.py
|
def TableDrivenAgentProgram(table):
"""This agent selects an action based on the percept sequence.
It is practical only for tiny domains.
To customize it, provide as table a dictionary of all
{percept_sequence:action} pairs. [Fig. 2.7]"""
percepts = []
def program(percept):
percepts.append(percept)
action = table.get(tuple(percepts))
return action
return program
|
def TableDrivenAgentProgram(table):
"""This agent selects an action based on the percept sequence.
It is practical only for tiny domains.
To customize it, provide as table a dictionary of all
{percept_sequence:action} pairs. [Fig. 2.7]"""
percepts = []
def program(percept):
percepts.append(percept)
action = table.get(tuple(percepts))
return action
return program
|
[
"This",
"agent",
"selects",
"an",
"action",
"based",
"on",
"the",
"percept",
"sequence",
".",
"It",
"is",
"practical",
"only",
"for",
"tiny",
"domains",
".",
"To",
"customize",
"it",
"provide",
"as",
"table",
"a",
"dictionary",
"of",
"all",
"{",
"percept_sequence",
":",
"action",
"}",
"pairs",
".",
"[",
"Fig",
".",
"2",
".",
"7",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L104-L114
|
[
"def",
"TableDrivenAgentProgram",
"(",
"table",
")",
":",
"percepts",
"=",
"[",
"]",
"def",
"program",
"(",
"percept",
")",
":",
"percepts",
".",
"append",
"(",
"percept",
")",
"action",
"=",
"table",
".",
"get",
"(",
"tuple",
"(",
"percepts",
")",
")",
"return",
"action",
"return",
"program"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
SimpleReflexAgentProgram
|
This agent takes action based solely on the percept. [Fig. 2.10]
|
aima/agents.py
|
def SimpleReflexAgentProgram(rules, interpret_input):
"This agent takes action based solely on the percept. [Fig. 2.10]"
def program(percept):
state = interpret_input(percept)
rule = rule_match(state, rules)
action = rule.action
return action
return program
|
def SimpleReflexAgentProgram(rules, interpret_input):
"This agent takes action based solely on the percept. [Fig. 2.10]"
def program(percept):
state = interpret_input(percept)
rule = rule_match(state, rules)
action = rule.action
return action
return program
|
[
"This",
"agent",
"takes",
"action",
"based",
"solely",
"on",
"the",
"percept",
".",
"[",
"Fig",
".",
"2",
".",
"10",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L122-L129
|
[
"def",
"SimpleReflexAgentProgram",
"(",
"rules",
",",
"interpret_input",
")",
":",
"def",
"program",
"(",
"percept",
")",
":",
"state",
"=",
"interpret_input",
"(",
"percept",
")",
"rule",
"=",
"rule_match",
"(",
"state",
",",
"rules",
")",
"action",
"=",
"rule",
".",
"action",
"return",
"action",
"return",
"program"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
ModelBasedReflexAgentProgram
|
This agent takes action based on the percept and state. [Fig. 2.12]
|
aima/agents.py
|
def ModelBasedReflexAgentProgram(rules, update_state):
"This agent takes action based on the percept and state. [Fig. 2.12]"
def program(percept):
program.state = update_state(program.state, program.action, percept)
rule = rule_match(program.state, rules)
action = rule.action
return action
program.state = program.action = None
return program
|
def ModelBasedReflexAgentProgram(rules, update_state):
"This agent takes action based on the percept and state. [Fig. 2.12]"
def program(percept):
program.state = update_state(program.state, program.action, percept)
rule = rule_match(program.state, rules)
action = rule.action
return action
program.state = program.action = None
return program
|
[
"This",
"agent",
"takes",
"action",
"based",
"on",
"the",
"percept",
"and",
"state",
".",
"[",
"Fig",
".",
"2",
".",
"12",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L131-L139
|
[
"def",
"ModelBasedReflexAgentProgram",
"(",
"rules",
",",
"update_state",
")",
":",
"def",
"program",
"(",
"percept",
")",
":",
"program",
".",
"state",
"=",
"update_state",
"(",
"program",
".",
"state",
",",
"program",
".",
"action",
",",
"percept",
")",
"rule",
"=",
"rule_match",
"(",
"program",
".",
"state",
",",
"rules",
")",
"action",
"=",
"rule",
".",
"action",
"return",
"action",
"program",
".",
"state",
"=",
"program",
".",
"action",
"=",
"None",
"return",
"program"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
TableDrivenVacuumAgent
|
[Fig. 2.3]
|
aima/agents.py
|
def TableDrivenVacuumAgent():
"[Fig. 2.3]"
table = {((loc_A, 'Clean'),): 'Right',
((loc_A, 'Dirty'),): 'Suck',
((loc_B, 'Clean'),): 'Left',
((loc_B, 'Dirty'),): 'Suck',
((loc_A, 'Clean'), (loc_A, 'Clean')): 'Right',
((loc_A, 'Clean'), (loc_A, 'Dirty')): 'Suck',
# ...
((loc_A, 'Clean'), (loc_A, 'Clean'), (loc_A, 'Clean')): 'Right',
((loc_A, 'Clean'), (loc_A, 'Clean'), (loc_A, 'Dirty')): 'Suck',
# ...
}
return Agent(TableDrivenAgentProgram(table))
|
def TableDrivenVacuumAgent():
"[Fig. 2.3]"
table = {((loc_A, 'Clean'),): 'Right',
((loc_A, 'Dirty'),): 'Suck',
((loc_B, 'Clean'),): 'Left',
((loc_B, 'Dirty'),): 'Suck',
((loc_A, 'Clean'), (loc_A, 'Clean')): 'Right',
((loc_A, 'Clean'), (loc_A, 'Dirty')): 'Suck',
# ...
((loc_A, 'Clean'), (loc_A, 'Clean'), (loc_A, 'Clean')): 'Right',
((loc_A, 'Clean'), (loc_A, 'Clean'), (loc_A, 'Dirty')): 'Suck',
# ...
}
return Agent(TableDrivenAgentProgram(table))
|
[
"[",
"Fig",
".",
"2",
".",
"3",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L157-L170
|
[
"def",
"TableDrivenVacuumAgent",
"(",
")",
":",
"table",
"=",
"{",
"(",
"(",
"loc_A",
",",
"'Clean'",
")",
",",
")",
":",
"'Right'",
",",
"(",
"(",
"loc_A",
",",
"'Dirty'",
")",
",",
")",
":",
"'Suck'",
",",
"(",
"(",
"loc_B",
",",
"'Clean'",
")",
",",
")",
":",
"'Left'",
",",
"(",
"(",
"loc_B",
",",
"'Dirty'",
")",
",",
")",
":",
"'Suck'",
",",
"(",
"(",
"loc_A",
",",
"'Clean'",
")",
",",
"(",
"loc_A",
",",
"'Clean'",
")",
")",
":",
"'Right'",
",",
"(",
"(",
"loc_A",
",",
"'Clean'",
")",
",",
"(",
"loc_A",
",",
"'Dirty'",
")",
")",
":",
"'Suck'",
",",
"# ...",
"(",
"(",
"loc_A",
",",
"'Clean'",
")",
",",
"(",
"loc_A",
",",
"'Clean'",
")",
",",
"(",
"loc_A",
",",
"'Clean'",
")",
")",
":",
"'Right'",
",",
"(",
"(",
"loc_A",
",",
"'Clean'",
")",
",",
"(",
"loc_A",
",",
"'Clean'",
")",
",",
"(",
"loc_A",
",",
"'Dirty'",
")",
")",
":",
"'Suck'",
",",
"# ...",
"}",
"return",
"Agent",
"(",
"TableDrivenAgentProgram",
"(",
"table",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
ReflexVacuumAgent
|
A reflex agent for the two-state vacuum environment. [Fig. 2.8]
|
aima/agents.py
|
def ReflexVacuumAgent():
"A reflex agent for the two-state vacuum environment. [Fig. 2.8]"
def program((location, status)):
if status == 'Dirty': return 'Suck'
elif location == loc_A: return 'Right'
elif location == loc_B: return 'Left'
return Agent(program)
|
def ReflexVacuumAgent():
"A reflex agent for the two-state vacuum environment. [Fig. 2.8]"
def program((location, status)):
if status == 'Dirty': return 'Suck'
elif location == loc_A: return 'Right'
elif location == loc_B: return 'Left'
return Agent(program)
|
[
"A",
"reflex",
"agent",
"for",
"the",
"two",
"-",
"state",
"vacuum",
"environment",
".",
"[",
"Fig",
".",
"2",
".",
"8",
"]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L173-L179
|
[
"def",
"ReflexVacuumAgent",
"(",
")",
":",
"def",
"program",
"(",
"(",
"location",
",",
"status",
")",
")",
":",
"if",
"status",
"==",
"'Dirty'",
":",
"return",
"'Suck'",
"elif",
"location",
"==",
"loc_A",
":",
"return",
"'Right'",
"elif",
"location",
"==",
"loc_B",
":",
"return",
"'Left'",
"return",
"Agent",
"(",
"program",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
ModelBasedVacuumAgent
|
An agent that keeps track of what locations are clean or dirty.
|
aima/agents.py
|
def ModelBasedVacuumAgent():
"An agent that keeps track of what locations are clean or dirty."
model = {loc_A: None, loc_B: None}
def program((location, status)):
"Same as ReflexVacuumAgent, except if everything is clean, do NoOp."
model[location] = status ## Update the model here
if model[loc_A] == model[loc_B] == 'Clean': return 'NoOp'
elif status == 'Dirty': return 'Suck'
elif location == loc_A: return 'Right'
elif location == loc_B: return 'Left'
return Agent(program)
|
def ModelBasedVacuumAgent():
"An agent that keeps track of what locations are clean or dirty."
model = {loc_A: None, loc_B: None}
def program((location, status)):
"Same as ReflexVacuumAgent, except if everything is clean, do NoOp."
model[location] = status ## Update the model here
if model[loc_A] == model[loc_B] == 'Clean': return 'NoOp'
elif status == 'Dirty': return 'Suck'
elif location == loc_A: return 'Right'
elif location == loc_B: return 'Left'
return Agent(program)
|
[
"An",
"agent",
"that",
"keeps",
"track",
"of",
"what",
"locations",
"are",
"clean",
"or",
"dirty",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L181-L191
|
[
"def",
"ModelBasedVacuumAgent",
"(",
")",
":",
"model",
"=",
"{",
"loc_A",
":",
"None",
",",
"loc_B",
":",
"None",
"}",
"def",
"program",
"(",
"(",
"location",
",",
"status",
")",
")",
":",
"\"Same as ReflexVacuumAgent, except if everything is clean, do NoOp.\"",
"model",
"[",
"location",
"]",
"=",
"status",
"## Update the model here",
"if",
"model",
"[",
"loc_A",
"]",
"==",
"model",
"[",
"loc_B",
"]",
"==",
"'Clean'",
":",
"return",
"'NoOp'",
"elif",
"status",
"==",
"'Dirty'",
":",
"return",
"'Suck'",
"elif",
"location",
"==",
"loc_A",
":",
"return",
"'Right'",
"elif",
"location",
"==",
"loc_B",
":",
"return",
"'Left'",
"return",
"Agent",
"(",
"program",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
compare_agents
|
See how well each of several agents do in n instances of an environment.
Pass in a factory (constructor) for environments, and several for agents.
Create n instances of the environment, and run each agent in copies of
each one for steps. Return a list of (agent, average-score) tuples.
|
aima/agents.py
|
def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
"""See how well each of several agents do in n instances of an environment.
Pass in a factory (constructor) for environments, and several for agents.
Create n instances of the environment, and run each agent in copies of
each one for steps. Return a list of (agent, average-score) tuples."""
envs = [EnvFactory() for i in range(n)]
return [(A, test_agent(A, steps, copy.deepcopy(envs)))
for A in AgentFactories]
|
def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
"""See how well each of several agents do in n instances of an environment.
Pass in a factory (constructor) for environments, and several for agents.
Create n instances of the environment, and run each agent in copies of
each one for steps. Return a list of (agent, average-score) tuples."""
envs = [EnvFactory() for i in range(n)]
return [(A, test_agent(A, steps, copy.deepcopy(envs)))
for A in AgentFactories]
|
[
"See",
"how",
"well",
"each",
"of",
"several",
"agents",
"do",
"in",
"n",
"instances",
"of",
"an",
"environment",
".",
"Pass",
"in",
"a",
"factory",
"(",
"constructor",
")",
"for",
"environments",
"and",
"several",
"for",
"agents",
".",
"Create",
"n",
"instances",
"of",
"the",
"environment",
"and",
"run",
"each",
"agent",
"in",
"copies",
"of",
"each",
"one",
"for",
"steps",
".",
"Return",
"a",
"list",
"of",
"(",
"agent",
"average",
"-",
"score",
")",
"tuples",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L491-L498
|
[
"def",
"compare_agents",
"(",
"EnvFactory",
",",
"AgentFactories",
",",
"n",
"=",
"10",
",",
"steps",
"=",
"1000",
")",
":",
"envs",
"=",
"[",
"EnvFactory",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"return",
"[",
"(",
"A",
",",
"test_agent",
"(",
"A",
",",
"steps",
",",
"copy",
".",
"deepcopy",
"(",
"envs",
")",
")",
")",
"for",
"A",
"in",
"AgentFactories",
"]"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Environment.step
|
Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method.
|
aima/agents.py
|
def step(self):
"""Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method."""
if not self.is_done():
actions = [agent.program(self.percept(agent))
for agent in self.agents]
for (agent, action) in zip(self.agents, actions):
self.execute_action(agent, action)
self.exogenous_change()
|
def step(self):
"""Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method."""
if not self.is_done():
actions = [agent.program(self.percept(agent))
for agent in self.agents]
for (agent, action) in zip(self.agents, actions):
self.execute_action(agent, action)
self.exogenous_change()
|
[
"Run",
"the",
"environment",
"for",
"one",
"time",
"step",
".",
"If",
"the",
"actions",
"and",
"exogenous",
"changes",
"are",
"independent",
"this",
"method",
"will",
"do",
".",
"If",
"there",
"are",
"interactions",
"between",
"them",
"you",
"ll",
"need",
"to",
"override",
"this",
"method",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L234-L244
|
[
"def",
"step",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_done",
"(",
")",
":",
"actions",
"=",
"[",
"agent",
".",
"program",
"(",
"self",
".",
"percept",
"(",
"agent",
")",
")",
"for",
"agent",
"in",
"self",
".",
"agents",
"]",
"for",
"(",
"agent",
",",
"action",
")",
"in",
"zip",
"(",
"self",
".",
"agents",
",",
"actions",
")",
":",
"self",
".",
"execute_action",
"(",
"agent",
",",
"action",
")",
"self",
".",
"exogenous_change",
"(",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Environment.run
|
Run the Environment for given number of time steps.
|
aima/agents.py
|
def run(self, steps=1000):
"Run the Environment for given number of time steps."
for step in range(steps):
if self.is_done(): return
self.step()
|
def run(self, steps=1000):
"Run the Environment for given number of time steps."
for step in range(steps):
if self.is_done(): return
self.step()
|
[
"Run",
"the",
"Environment",
"for",
"given",
"number",
"of",
"time",
"steps",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L246-L250
|
[
"def",
"run",
"(",
"self",
",",
"steps",
"=",
"1000",
")",
":",
"for",
"step",
"in",
"range",
"(",
"steps",
")",
":",
"if",
"self",
".",
"is_done",
"(",
")",
":",
"return",
"self",
".",
"step",
"(",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Environment.list_things_at
|
Return all things exactly at a given location.
|
aima/agents.py
|
def list_things_at(self, location, tclass=Thing):
"Return all things exactly at a given location."
return [thing for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
|
def list_things_at(self, location, tclass=Thing):
"Return all things exactly at a given location."
return [thing for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
|
[
"Return",
"all",
"things",
"exactly",
"at",
"a",
"given",
"location",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L252-L255
|
[
"def",
"list_things_at",
"(",
"self",
",",
"location",
",",
"tclass",
"=",
"Thing",
")",
":",
"return",
"[",
"thing",
"for",
"thing",
"in",
"self",
".",
"things",
"if",
"thing",
".",
"location",
"==",
"location",
"and",
"isinstance",
"(",
"thing",
",",
"tclass",
")",
"]"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Environment.add_thing
|
Add a thing to the environment, setting its location. For
convenience, if thing is an agent program we make a new agent
for it. (Shouldn't need to override this.
|
aima/agents.py
|
def add_thing(self, thing, location=None):
"""Add a thing to the environment, setting its location. For
convenience, if thing is an agent program we make a new agent
for it. (Shouldn't need to override this."""
if not isinstance(thing, Thing):
thing = Agent(thing)
assert thing not in self.things, "Don't add the same thing twice"
thing.location = location or self.default_location(thing)
self.things.append(thing)
if isinstance(thing, Agent):
thing.performance = 0
self.agents.append(thing)
|
def add_thing(self, thing, location=None):
"""Add a thing to the environment, setting its location. For
convenience, if thing is an agent program we make a new agent
for it. (Shouldn't need to override this."""
if not isinstance(thing, Thing):
thing = Agent(thing)
assert thing not in self.things, "Don't add the same thing twice"
thing.location = location or self.default_location(thing)
self.things.append(thing)
if isinstance(thing, Agent):
thing.performance = 0
self.agents.append(thing)
|
[
"Add",
"a",
"thing",
"to",
"the",
"environment",
"setting",
"its",
"location",
".",
"For",
"convenience",
"if",
"thing",
"is",
"an",
"agent",
"program",
"we",
"make",
"a",
"new",
"agent",
"for",
"it",
".",
"(",
"Shouldn",
"t",
"need",
"to",
"override",
"this",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L262-L273
|
[
"def",
"add_thing",
"(",
"self",
",",
"thing",
",",
"location",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"thing",
",",
"Thing",
")",
":",
"thing",
"=",
"Agent",
"(",
"thing",
")",
"assert",
"thing",
"not",
"in",
"self",
".",
"things",
",",
"\"Don't add the same thing twice\"",
"thing",
".",
"location",
"=",
"location",
"or",
"self",
".",
"default_location",
"(",
"thing",
")",
"self",
".",
"things",
".",
"append",
"(",
"thing",
")",
"if",
"isinstance",
"(",
"thing",
",",
"Agent",
")",
":",
"thing",
".",
"performance",
"=",
"0",
"self",
".",
"agents",
".",
"append",
"(",
"thing",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Environment.delete_thing
|
Remove a thing from the environment.
|
aima/agents.py
|
def delete_thing(self, thing):
"""Remove a thing from the environment."""
try:
self.things.remove(thing)
except ValueError, e:
print e
print " in Environment delete_thing"
print " Thing to be removed: %s at %s" % (thing, thing.location)
print " from list: %s" % [(thing, thing.location)
for thing in self.things]
if thing in self.agents:
self.agents.remove(thing)
|
def delete_thing(self, thing):
"""Remove a thing from the environment."""
try:
self.things.remove(thing)
except ValueError, e:
print e
print " in Environment delete_thing"
print " Thing to be removed: %s at %s" % (thing, thing.location)
print " from list: %s" % [(thing, thing.location)
for thing in self.things]
if thing in self.agents:
self.agents.remove(thing)
|
[
"Remove",
"a",
"thing",
"from",
"the",
"environment",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L275-L286
|
[
"def",
"delete_thing",
"(",
"self",
",",
"thing",
")",
":",
"try",
":",
"self",
".",
"things",
".",
"remove",
"(",
"thing",
")",
"except",
"ValueError",
",",
"e",
":",
"print",
"e",
"print",
"\" in Environment delete_thing\"",
"print",
"\" Thing to be removed: %s at %s\"",
"%",
"(",
"thing",
",",
"thing",
".",
"location",
")",
"print",
"\" from list: %s\"",
"%",
"[",
"(",
"thing",
",",
"thing",
".",
"location",
")",
"for",
"thing",
"in",
"self",
".",
"things",
"]",
"if",
"thing",
"in",
"self",
".",
"agents",
":",
"self",
".",
"agents",
".",
"remove",
"(",
"thing",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
XYEnvironment.things_near
|
Return all things within radius of location.
|
aima/agents.py
|
def things_near(self, location, radius=None):
"Return all things within radius of location."
if radius is None: radius = self.perceptible_distance
radius2 = radius * radius
return [thing for thing in self.things
if distance2(location, thing.location) <= radius2]
|
def things_near(self, location, radius=None):
"Return all things within radius of location."
if radius is None: radius = self.perceptible_distance
radius2 = radius * radius
return [thing for thing in self.things
if distance2(location, thing.location) <= radius2]
|
[
"Return",
"all",
"things",
"within",
"radius",
"of",
"location",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L301-L306
|
[
"def",
"things_near",
"(",
"self",
",",
"location",
",",
"radius",
"=",
"None",
")",
":",
"if",
"radius",
"is",
"None",
":",
"radius",
"=",
"self",
".",
"perceptible_distance",
"radius2",
"=",
"radius",
"*",
"radius",
"return",
"[",
"thing",
"for",
"thing",
"in",
"self",
".",
"things",
"if",
"distance2",
"(",
"location",
",",
"thing",
".",
"location",
")",
"<=",
"radius2",
"]"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
XYEnvironment.percept
|
By default, agent perceives things within a default radius.
|
aima/agents.py
|
def percept(self, agent):
"By default, agent perceives things within a default radius."
return [self.thing_percept(thing, agent)
for thing in self.things_near(agent.location)]
|
def percept(self, agent):
"By default, agent perceives things within a default radius."
return [self.thing_percept(thing, agent)
for thing in self.things_near(agent.location)]
|
[
"By",
"default",
"agent",
"perceives",
"things",
"within",
"a",
"default",
"radius",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L310-L313
|
[
"def",
"percept",
"(",
"self",
",",
"agent",
")",
":",
"return",
"[",
"self",
".",
"thing_percept",
"(",
"thing",
",",
"agent",
")",
"for",
"thing",
"in",
"self",
".",
"things_near",
"(",
"agent",
".",
"location",
")",
"]"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
XYEnvironment.move_to
|
Move a thing to a new location.
|
aima/agents.py
|
def move_to(self, thing, destination):
"Move a thing to a new location."
thing.bump = self.some_things_at(destination, Obstacle)
if not thing.bump:
thing.location = destination
for o in self.observers:
o.thing_moved(thing)
|
def move_to(self, thing, destination):
"Move a thing to a new location."
thing.bump = self.some_things_at(destination, Obstacle)
if not thing.bump:
thing.location = destination
for o in self.observers:
o.thing_moved(thing)
|
[
"Move",
"a",
"thing",
"to",
"a",
"new",
"location",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L339-L345
|
[
"def",
"move_to",
"(",
"self",
",",
"thing",
",",
"destination",
")",
":",
"thing",
".",
"bump",
"=",
"self",
".",
"some_things_at",
"(",
"destination",
",",
"Obstacle",
")",
"if",
"not",
"thing",
".",
"bump",
":",
"thing",
".",
"location",
"=",
"destination",
"for",
"o",
"in",
"self",
".",
"observers",
":",
"o",
".",
"thing_moved",
"(",
"thing",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
XYEnvironment.add_walls
|
Put walls around the entire perimeter of the grid.
|
aima/agents.py
|
def add_walls(self):
"Put walls around the entire perimeter of the grid."
for x in range(self.width):
self.add_thing(Wall(), (x, 0))
self.add_thing(Wall(), (x, self.height-1))
for y in range(self.height):
self.add_thing(Wall(), (0, y))
self.add_thing(Wall(), (self.width-1, y))
|
def add_walls(self):
"Put walls around the entire perimeter of the grid."
for x in range(self.width):
self.add_thing(Wall(), (x, 0))
self.add_thing(Wall(), (x, self.height-1))
for y in range(self.height):
self.add_thing(Wall(), (0, y))
self.add_thing(Wall(), (self.width-1, y))
|
[
"Put",
"walls",
"around",
"the",
"entire",
"perimeter",
"of",
"the",
"grid",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L360-L367
|
[
"def",
"add_walls",
"(",
"self",
")",
":",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"width",
")",
":",
"self",
".",
"add_thing",
"(",
"Wall",
"(",
")",
",",
"(",
"x",
",",
"0",
")",
")",
"self",
".",
"add_thing",
"(",
"Wall",
"(",
")",
",",
"(",
"x",
",",
"self",
".",
"height",
"-",
"1",
")",
")",
"for",
"y",
"in",
"range",
"(",
"self",
".",
"height",
")",
":",
"self",
".",
"add_thing",
"(",
"Wall",
"(",
")",
",",
"(",
"0",
",",
"y",
")",
")",
"self",
".",
"add_thing",
"(",
"Wall",
"(",
")",
",",
"(",
"self",
".",
"width",
"-",
"1",
",",
"y",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
VacuumEnvironment.percept
|
The percept is a tuple of ('Dirty' or 'Clean', 'Bump' or 'None').
Unlike the TrivialVacuumEnvironment, location is NOT perceived.
|
aima/agents.py
|
def percept(self, agent):
"""The percept is a tuple of ('Dirty' or 'Clean', 'Bump' or 'None').
Unlike the TrivialVacuumEnvironment, location is NOT perceived."""
status = if_(self.some_things_at(agent.location, Dirt),
'Dirty', 'Clean')
bump = if_(agent.bump, 'Bump', 'None')
return (status, bump)
|
def percept(self, agent):
"""The percept is a tuple of ('Dirty' or 'Clean', 'Bump' or 'None').
Unlike the TrivialVacuumEnvironment, location is NOT perceived."""
status = if_(self.some_things_at(agent.location, Dirt),
'Dirty', 'Clean')
bump = if_(agent.bump, 'Bump', 'None')
return (status, bump)
|
[
"The",
"percept",
"is",
"a",
"tuple",
"of",
"(",
"Dirty",
"or",
"Clean",
"Bump",
"or",
"None",
")",
".",
"Unlike",
"the",
"TrivialVacuumEnvironment",
"location",
"is",
"NOT",
"perceived",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L410-L416
|
[
"def",
"percept",
"(",
"self",
",",
"agent",
")",
":",
"status",
"=",
"if_",
"(",
"self",
".",
"some_things_at",
"(",
"agent",
".",
"location",
",",
"Dirt",
")",
",",
"'Dirty'",
",",
"'Clean'",
")",
"bump",
"=",
"if_",
"(",
"agent",
".",
"bump",
",",
"'Bump'",
",",
"'None'",
")",
"return",
"(",
"status",
",",
"bump",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
TrivialVacuumEnvironment.execute_action
|
Change agent's location and/or location's status; track performance.
Score 10 for each dirt cleaned; -1 for each move.
|
aima/agents.py
|
def execute_action(self, agent, action):
"""Change agent's location and/or location's status; track performance.
Score 10 for each dirt cleaned; -1 for each move."""
if action == 'Right':
agent.location = loc_B
agent.performance -= 1
elif action == 'Left':
agent.location = loc_A
agent.performance -= 1
elif action == 'Suck':
if self.status[agent.location] == 'Dirty':
agent.performance += 10
self.status[agent.location] = 'Clean'
|
def execute_action(self, agent, action):
"""Change agent's location and/or location's status; track performance.
Score 10 for each dirt cleaned; -1 for each move."""
if action == 'Right':
agent.location = loc_B
agent.performance -= 1
elif action == 'Left':
agent.location = loc_A
agent.performance -= 1
elif action == 'Suck':
if self.status[agent.location] == 'Dirty':
agent.performance += 10
self.status[agent.location] = 'Clean'
|
[
"Change",
"agent",
"s",
"location",
"and",
"/",
"or",
"location",
"s",
"status",
";",
"track",
"performance",
".",
"Score",
"10",
"for",
"each",
"dirt",
"cleaned",
";",
"-",
"1",
"for",
"each",
"move",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L450-L462
|
[
"def",
"execute_action",
"(",
"self",
",",
"agent",
",",
"action",
")",
":",
"if",
"action",
"==",
"'Right'",
":",
"agent",
".",
"location",
"=",
"loc_B",
"agent",
".",
"performance",
"-=",
"1",
"elif",
"action",
"==",
"'Left'",
":",
"agent",
".",
"location",
"=",
"loc_A",
"agent",
".",
"performance",
"-=",
"1",
"elif",
"action",
"==",
"'Suck'",
":",
"if",
"self",
".",
"status",
"[",
"agent",
".",
"location",
"]",
"==",
"'Dirty'",
":",
"agent",
".",
"performance",
"+=",
"10",
"self",
".",
"status",
"[",
"agent",
".",
"location",
"]",
"=",
"'Clean'"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Rules
|
Create a dictionary mapping symbols to alternative sequences.
>>> Rules(A = "B C | D E")
{'A': [['B', 'C'], ['D', 'E']]}
|
aima/nlp.py
|
def Rules(**rules):
"""Create a dictionary mapping symbols to alternative sequences.
>>> Rules(A = "B C | D E")
{'A': [['B', 'C'], ['D', 'E']]}
"""
for (lhs, rhs) in rules.items():
rules[lhs] = [alt.strip().split() for alt in rhs.split('|')]
return rules
|
def Rules(**rules):
"""Create a dictionary mapping symbols to alternative sequences.
>>> Rules(A = "B C | D E")
{'A': [['B', 'C'], ['D', 'E']]}
"""
for (lhs, rhs) in rules.items():
rules[lhs] = [alt.strip().split() for alt in rhs.split('|')]
return rules
|
[
"Create",
"a",
"dictionary",
"mapping",
"symbols",
"to",
"alternative",
"sequences",
".",
">>>",
"Rules",
"(",
"A",
"=",
"B",
"C",
"|",
"D",
"E",
")",
"{",
"A",
":",
"[[",
"B",
"C",
"]",
"[",
"D",
"E",
"]]",
"}"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L11-L18
|
[
"def",
"Rules",
"(",
"*",
"*",
"rules",
")",
":",
"for",
"(",
"lhs",
",",
"rhs",
")",
"in",
"rules",
".",
"items",
"(",
")",
":",
"rules",
"[",
"lhs",
"]",
"=",
"[",
"alt",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"for",
"alt",
"in",
"rhs",
".",
"split",
"(",
"'|'",
")",
"]",
"return",
"rules"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Lexicon
|
Create a dictionary mapping symbols to alternative words.
>>> Lexicon(Art = "the | a | an")
{'Art': ['the', 'a', 'an']}
|
aima/nlp.py
|
def Lexicon(**rules):
"""Create a dictionary mapping symbols to alternative words.
>>> Lexicon(Art = "the | a | an")
{'Art': ['the', 'a', 'an']}
"""
for (lhs, rhs) in rules.items():
rules[lhs] = [word.strip() for word in rhs.split('|')]
return rules
|
def Lexicon(**rules):
"""Create a dictionary mapping symbols to alternative words.
>>> Lexicon(Art = "the | a | an")
{'Art': ['the', 'a', 'an']}
"""
for (lhs, rhs) in rules.items():
rules[lhs] = [word.strip() for word in rhs.split('|')]
return rules
|
[
"Create",
"a",
"dictionary",
"mapping",
"symbols",
"to",
"alternative",
"words",
".",
">>>",
"Lexicon",
"(",
"Art",
"=",
"the",
"|",
"a",
"|",
"an",
")",
"{",
"Art",
":",
"[",
"the",
"a",
"an",
"]",
"}"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L20-L27
|
[
"def",
"Lexicon",
"(",
"*",
"*",
"rules",
")",
":",
"for",
"(",
"lhs",
",",
"rhs",
")",
"in",
"rules",
".",
"items",
"(",
")",
":",
"rules",
"[",
"lhs",
"]",
"=",
"[",
"word",
".",
"strip",
"(",
")",
"for",
"word",
"in",
"rhs",
".",
"split",
"(",
"'|'",
")",
"]",
"return",
"rules"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
generate_random
|
Replace each token in s by a random entry in grammar (recursively).
This is useful for testing a grammar, e.g. generate_random(E_)
|
aima/nlp.py
|
def generate_random(grammar=E_, s='S'):
"""Replace each token in s by a random entry in grammar (recursively).
This is useful for testing a grammar, e.g. generate_random(E_)"""
import random
def rewrite(tokens, into):
for token in tokens:
if token in grammar.rules:
rewrite(random.choice(grammar.rules[token]), into)
elif token in grammar.lexicon:
into.append(random.choice(grammar.lexicon[token]))
else:
into.append(token)
return into
return ' '.join(rewrite(s.split(), []))
|
def generate_random(grammar=E_, s='S'):
"""Replace each token in s by a random entry in grammar (recursively).
This is useful for testing a grammar, e.g. generate_random(E_)"""
import random
def rewrite(tokens, into):
for token in tokens:
if token in grammar.rules:
rewrite(random.choice(grammar.rules[token]), into)
elif token in grammar.lexicon:
into.append(random.choice(grammar.lexicon[token]))
else:
into.append(token)
return into
return ' '.join(rewrite(s.split(), []))
|
[
"Replace",
"each",
"token",
"in",
"s",
"by",
"a",
"random",
"entry",
"in",
"grammar",
"(",
"recursively",
")",
".",
"This",
"is",
"useful",
"for",
"testing",
"a",
"grammar",
"e",
".",
"g",
".",
"generate_random",
"(",
"E_",
")"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L89-L104
|
[
"def",
"generate_random",
"(",
"grammar",
"=",
"E_",
",",
"s",
"=",
"'S'",
")",
":",
"import",
"random",
"def",
"rewrite",
"(",
"tokens",
",",
"into",
")",
":",
"for",
"token",
"in",
"tokens",
":",
"if",
"token",
"in",
"grammar",
".",
"rules",
":",
"rewrite",
"(",
"random",
".",
"choice",
"(",
"grammar",
".",
"rules",
"[",
"token",
"]",
")",
",",
"into",
")",
"elif",
"token",
"in",
"grammar",
".",
"lexicon",
":",
"into",
".",
"append",
"(",
"random",
".",
"choice",
"(",
"grammar",
".",
"lexicon",
"[",
"token",
"]",
")",
")",
"else",
":",
"into",
".",
"append",
"(",
"token",
")",
"return",
"into",
"return",
"' '",
".",
"join",
"(",
"rewrite",
"(",
"s",
".",
"split",
"(",
")",
",",
"[",
"]",
")",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Chart.parses
|
Return a list of parses; words can be a list or string.
>>> chart = Chart(E_NP_)
>>> chart.parses('happy man', 'NP')
[[0, 2, 'NP', [('Adj', 'happy'), [1, 2, 'NP', [('N', 'man')], []]], []]]
|
aima/nlp.py
|
def parses(self, words, S='S'):
"""Return a list of parses; words can be a list or string.
>>> chart = Chart(E_NP_)
>>> chart.parses('happy man', 'NP')
[[0, 2, 'NP', [('Adj', 'happy'), [1, 2, 'NP', [('N', 'man')], []]], []]]
"""
if isinstance(words, str):
words = words.split()
self.parse(words, S)
# Return all the parses that span the whole input
# 'span the whole input' => begin at 0, end at len(words)
return [[i, j, S, found, []]
for (i, j, lhs, found, expects) in self.chart[len(words)]
# assert j == len(words)
if i == 0 and lhs == S and expects == []]
|
def parses(self, words, S='S'):
"""Return a list of parses; words can be a list or string.
>>> chart = Chart(E_NP_)
>>> chart.parses('happy man', 'NP')
[[0, 2, 'NP', [('Adj', 'happy'), [1, 2, 'NP', [('N', 'man')], []]], []]]
"""
if isinstance(words, str):
words = words.split()
self.parse(words, S)
# Return all the parses that span the whole input
# 'span the whole input' => begin at 0, end at len(words)
return [[i, j, S, found, []]
for (i, j, lhs, found, expects) in self.chart[len(words)]
# assert j == len(words)
if i == 0 and lhs == S and expects == []]
|
[
"Return",
"a",
"list",
"of",
"parses",
";",
"words",
"can",
"be",
"a",
"list",
"or",
"string",
".",
">>>",
"chart",
"=",
"Chart",
"(",
"E_NP_",
")",
">>>",
"chart",
".",
"parses",
"(",
"happy",
"man",
"NP",
")",
"[[",
"0",
"2",
"NP",
"[",
"(",
"Adj",
"happy",
")",
"[",
"1",
"2",
"NP",
"[",
"(",
"N",
"man",
")",
"]",
"[]",
"]]",
"[]",
"]]"
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L123-L137
|
[
"def",
"parses",
"(",
"self",
",",
"words",
",",
"S",
"=",
"'S'",
")",
":",
"if",
"isinstance",
"(",
"words",
",",
"str",
")",
":",
"words",
"=",
"words",
".",
"split",
"(",
")",
"self",
".",
"parse",
"(",
"words",
",",
"S",
")",
"# Return all the parses that span the whole input",
"# 'span the whole input' => begin at 0, end at len(words)",
"return",
"[",
"[",
"i",
",",
"j",
",",
"S",
",",
"found",
",",
"[",
"]",
"]",
"for",
"(",
"i",
",",
"j",
",",
"lhs",
",",
"found",
",",
"expects",
")",
"in",
"self",
".",
"chart",
"[",
"len",
"(",
"words",
")",
"]",
"# assert j == len(words)",
"if",
"i",
"==",
"0",
"and",
"lhs",
"==",
"S",
"and",
"expects",
"==",
"[",
"]",
"]"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Chart.parse
|
Parse a list of words; according to the grammar.
Leave results in the chart.
|
aima/nlp.py
|
def parse(self, words, S='S'):
"""Parse a list of words; according to the grammar.
Leave results in the chart."""
self.chart = [[] for i in range(len(words)+1)]
self.add_edge([0, 0, 'S_', [], [S]])
for i in range(len(words)):
self.scanner(i, words[i])
return self.chart
|
def parse(self, words, S='S'):
"""Parse a list of words; according to the grammar.
Leave results in the chart."""
self.chart = [[] for i in range(len(words)+1)]
self.add_edge([0, 0, 'S_', [], [S]])
for i in range(len(words)):
self.scanner(i, words[i])
return self.chart
|
[
"Parse",
"a",
"list",
"of",
"words",
";",
"according",
"to",
"the",
"grammar",
".",
"Leave",
"results",
"in",
"the",
"chart",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L139-L146
|
[
"def",
"parse",
"(",
"self",
",",
"words",
",",
"S",
"=",
"'S'",
")",
":",
"self",
".",
"chart",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"words",
")",
"+",
"1",
")",
"]",
"self",
".",
"add_edge",
"(",
"[",
"0",
",",
"0",
",",
"'S_'",
",",
"[",
"]",
",",
"[",
"S",
"]",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"words",
")",
")",
":",
"self",
".",
"scanner",
"(",
"i",
",",
"words",
"[",
"i",
"]",
")",
"return",
"self",
".",
"chart"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
valid
|
Chart.add_edge
|
Add edge to chart, and see if it extends or predicts another edge.
|
aima/nlp.py
|
def add_edge(self, edge):
"Add edge to chart, and see if it extends or predicts another edge."
start, end, lhs, found, expects = edge
if edge not in self.chart[end]:
self.chart[end].append(edge)
if self.trace:
print '%10s: added %s' % (caller(2), edge)
if not expects:
self.extender(edge)
else:
self.predictor(edge)
|
def add_edge(self, edge):
"Add edge to chart, and see if it extends or predicts another edge."
start, end, lhs, found, expects = edge
if edge not in self.chart[end]:
self.chart[end].append(edge)
if self.trace:
print '%10s: added %s' % (caller(2), edge)
if not expects:
self.extender(edge)
else:
self.predictor(edge)
|
[
"Add",
"edge",
"to",
"chart",
"and",
"see",
"if",
"it",
"extends",
"or",
"predicts",
"another",
"edge",
"."
] |
hobson/aima
|
python
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L148-L158
|
[
"def",
"add_edge",
"(",
"self",
",",
"edge",
")",
":",
"start",
",",
"end",
",",
"lhs",
",",
"found",
",",
"expects",
"=",
"edge",
"if",
"edge",
"not",
"in",
"self",
".",
"chart",
"[",
"end",
"]",
":",
"self",
".",
"chart",
"[",
"end",
"]",
".",
"append",
"(",
"edge",
")",
"if",
"self",
".",
"trace",
":",
"print",
"'%10s: added %s'",
"%",
"(",
"caller",
"(",
"2",
")",
",",
"edge",
")",
"if",
"not",
"expects",
":",
"self",
".",
"extender",
"(",
"edge",
")",
"else",
":",
"self",
".",
"predictor",
"(",
"edge",
")"
] |
3572b2fb92039b4a1abe384be8545560fbd3d470
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.