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
associate
Given an associative op, return an expression with the same meaning as Expr(op, *args), but flattened -- that is, with nested instances of the same op promoted to the top level. >>> associate('&', [(A&B),(B|C),(B&C)]) (A & B & (B | C) & B & C) >>> associate('|', [A|(B|(C|(A&B)))]) (A | B | C | (A & B))
aima/logic.py
def associate(op, args): """Given an associative op, return an expression with the same meaning as Expr(op, *args), but flattened -- that is, with nested instances of the same op promoted to the top level. >>> associate('&', [(A&B),(B|C),(B&C)]) (A & B & (B | C) & B & C) >>> associate('|', [A|(B|(C|(A&B)))]) (A | B | C | (A & B)) """ args = dissociate(op, args) if len(args) == 0: return _op_identity[op] elif len(args) == 1: return args[0] else: return Expr(op, *args)
def associate(op, args): """Given an associative op, return an expression with the same meaning as Expr(op, *args), but flattened -- that is, with nested instances of the same op promoted to the top level. >>> associate('&', [(A&B),(B|C),(B&C)]) (A & B & (B | C) & B & C) >>> associate('|', [A|(B|(C|(A&B)))]) (A | B | C | (A & B)) """ args = dissociate(op, args) if len(args) == 0: return _op_identity[op] elif len(args) == 1: return args[0] else: return Expr(op, *args)
[ "Given", "an", "associative", "op", "return", "an", "expression", "with", "the", "same", "meaning", "as", "Expr", "(", "op", "*", "args", ")", "but", "flattened", "--", "that", "is", "with", "nested", "instances", "of", "the", "same", "op", "promoted", "to", "the", "top", "level", ".", ">>>", "associate", "(", "&", "[", "(", "A&B", ")", "(", "B|C", ")", "(", "B&C", ")", "]", ")", "(", "A", "&", "B", "&", "(", "B", "|", "C", ")", "&", "B", "&", "C", ")", ">>>", "associate", "(", "|", "[", "A|", "(", "B|", "(", "C|", "(", "A&B", ")))", "]", ")", "(", "A", "|", "B", "|", "C", "|", "(", "A", "&", "B", "))" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L497-L512
[ "def", "associate", "(", "op", ",", "args", ")", ":", "args", "=", "dissociate", "(", "op", ",", "args", ")", "if", "len", "(", "args", ")", "==", "0", ":", "return", "_op_identity", "[", "op", "]", "elif", "len", "(", "args", ")", "==", "1", ":", "return", "args", "[", "0", "]", "else", ":", "return", "Expr", "(", "op", ",", "*", "args", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
dissociate
Given an associative op, return a flattened list result such that Expr(op, *result) means the same as Expr(op, *args).
aima/logic.py
def dissociate(op, args): """Given an associative op, return a flattened list result such that Expr(op, *result) means the same as Expr(op, *args).""" result = [] def collect(subargs): for arg in subargs: if arg.op == op: collect(arg.args) else: result.append(arg) collect(args) return result
def dissociate(op, args): """Given an associative op, return a flattened list result such that Expr(op, *result) means the same as Expr(op, *args).""" result = [] def collect(subargs): for arg in subargs: if arg.op == op: collect(arg.args) else: result.append(arg) collect(args) return result
[ "Given", "an", "associative", "op", "return", "a", "flattened", "list", "result", "such", "that", "Expr", "(", "op", "*", "result", ")", "means", "the", "same", "as", "Expr", "(", "op", "*", "args", ")", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L516-L525
[ "def", "dissociate", "(", "op", ",", "args", ")", ":", "result", "=", "[", "]", "def", "collect", "(", "subargs", ")", ":", "for", "arg", "in", "subargs", ":", "if", "arg", ".", "op", "==", "op", ":", "collect", "(", "arg", ".", "args", ")", "else", ":", "result", ".", "append", "(", "arg", ")", "collect", "(", "args", ")", "return", "result" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
pl_resolution
Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12]
aima/logic.py
def pl_resolution(KB, alpha): "Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12]" clauses = KB.clauses + conjuncts(to_cnf(~alpha)) new = set() while True: n = len(clauses) pairs = [(clauses[i], clauses[j]) for i in range(n) for j in range(i+1, n)] for (ci, cj) in pairs: resolvents = pl_resolve(ci, cj) if FALSE in resolvents: return True new = new.union(set(resolvents)) if new.issubset(set(clauses)): return False for c in new: if c not in clauses: clauses.append(c)
def pl_resolution(KB, alpha): "Propositional-logic resolution: say if alpha follows from KB. [Fig. 7.12]" clauses = KB.clauses + conjuncts(to_cnf(~alpha)) new = set() while True: n = len(clauses) pairs = [(clauses[i], clauses[j]) for i in range(n) for j in range(i+1, n)] for (ci, cj) in pairs: resolvents = pl_resolve(ci, cj) if FALSE in resolvents: return True new = new.union(set(resolvents)) if new.issubset(set(clauses)): return False for c in new: if c not in clauses: clauses.append(c)
[ "Propositional", "-", "logic", "resolution", ":", "say", "if", "alpha", "follows", "from", "KB", ".", "[", "Fig", ".", "7", ".", "12", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L547-L561
[ "def", "pl_resolution", "(", "KB", ",", "alpha", ")", ":", "clauses", "=", "KB", ".", "clauses", "+", "conjuncts", "(", "to_cnf", "(", "~", "alpha", ")", ")", "new", "=", "set", "(", ")", "while", "True", ":", "n", "=", "len", "(", "clauses", ")", "pairs", "=", "[", "(", "clauses", "[", "i", "]", ",", "clauses", "[", "j", "]", ")", "for", "i", "in", "range", "(", "n", ")", "for", "j", "in", "range", "(", "i", "+", "1", ",", "n", ")", "]", "for", "(", "ci", ",", "cj", ")", "in", "pairs", ":", "resolvents", "=", "pl_resolve", "(", "ci", ",", "cj", ")", "if", "FALSE", "in", "resolvents", ":", "return", "True", "new", "=", "new", ".", "union", "(", "set", "(", "resolvents", ")", ")", "if", "new", ".", "issubset", "(", "set", "(", "clauses", ")", ")", ":", "return", "False", "for", "c", "in", "new", ":", "if", "c", "not", "in", "clauses", ":", "clauses", ".", "append", "(", "c", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
pl_resolve
Return all clauses that can be obtained by resolving clauses ci and cj. >>> for res in pl_resolve(to_cnf(A|B|C), to_cnf(~B|~C|F)): ... ppset(disjuncts(res)) set([A, C, F, ~C]) set([A, B, F, ~B])
aima/logic.py
def pl_resolve(ci, cj): """Return all clauses that can be obtained by resolving clauses ci and cj. >>> for res in pl_resolve(to_cnf(A|B|C), to_cnf(~B|~C|F)): ... ppset(disjuncts(res)) set([A, C, F, ~C]) set([A, B, F, ~B]) """ clauses = [] for di in disjuncts(ci): for dj in disjuncts(cj): if di == ~dj or ~di == dj: dnew = unique(removeall(di, disjuncts(ci)) + removeall(dj, disjuncts(cj))) clauses.append(associate('|', dnew)) return clauses
def pl_resolve(ci, cj): """Return all clauses that can be obtained by resolving clauses ci and cj. >>> for res in pl_resolve(to_cnf(A|B|C), to_cnf(~B|~C|F)): ... ppset(disjuncts(res)) set([A, C, F, ~C]) set([A, B, F, ~B]) """ clauses = [] for di in disjuncts(ci): for dj in disjuncts(cj): if di == ~dj or ~di == dj: dnew = unique(removeall(di, disjuncts(ci)) + removeall(dj, disjuncts(cj))) clauses.append(associate('|', dnew)) return clauses
[ "Return", "all", "clauses", "that", "can", "be", "obtained", "by", "resolving", "clauses", "ci", "and", "cj", ".", ">>>", "for", "res", "in", "pl_resolve", "(", "to_cnf", "(", "A|B|C", ")", "to_cnf", "(", "~B|~C|F", "))", ":", "...", "ppset", "(", "disjuncts", "(", "res", "))", "set", "(", "[", "A", "C", "F", "~C", "]", ")", "set", "(", "[", "A", "B", "F", "~B", "]", ")" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L563-L577
[ "def", "pl_resolve", "(", "ci", ",", "cj", ")", ":", "clauses", "=", "[", "]", "for", "di", "in", "disjuncts", "(", "ci", ")", ":", "for", "dj", "in", "disjuncts", "(", "cj", ")", ":", "if", "di", "==", "~", "dj", "or", "~", "di", "==", "dj", ":", "dnew", "=", "unique", "(", "removeall", "(", "di", ",", "disjuncts", "(", "ci", ")", ")", "+", "removeall", "(", "dj", ",", "disjuncts", "(", "cj", ")", ")", ")", "clauses", ".", "append", "(", "associate", "(", "'|'", ",", "dnew", ")", ")", "return", "clauses" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
pl_fc_entails
Use forward chaining to see if a PropDefiniteKB entails symbol q. [Fig. 7.15] >>> pl_fc_entails(Fig[7,15], expr('Q')) True
aima/logic.py
def pl_fc_entails(KB, q): """Use forward chaining to see if a PropDefiniteKB entails symbol q. [Fig. 7.15] >>> pl_fc_entails(Fig[7,15], expr('Q')) True """ count = dict([(c, len(conjuncts(c.args[0]))) for c in KB.clauses if c.op == '>>']) inferred = DefaultDict(False) agenda = [s for s in KB.clauses if is_prop_symbol(s.op)] while agenda: p = agenda.pop() if p == q: return True if not inferred[p]: inferred[p] = True for c in KB.clauses_with_premise(p): count[c] -= 1 if count[c] == 0: agenda.append(c.args[1]) return False
def pl_fc_entails(KB, q): """Use forward chaining to see if a PropDefiniteKB entails symbol q. [Fig. 7.15] >>> pl_fc_entails(Fig[7,15], expr('Q')) True """ count = dict([(c, len(conjuncts(c.args[0]))) for c in KB.clauses if c.op == '>>']) inferred = DefaultDict(False) agenda = [s for s in KB.clauses if is_prop_symbol(s.op)] while agenda: p = agenda.pop() if p == q: return True if not inferred[p]: inferred[p] = True for c in KB.clauses_with_premise(p): count[c] -= 1 if count[c] == 0: agenda.append(c.args[1]) return False
[ "Use", "forward", "chaining", "to", "see", "if", "a", "PropDefiniteKB", "entails", "symbol", "q", ".", "[", "Fig", ".", "7", ".", "15", "]", ">>>", "pl_fc_entails", "(", "Fig", "[", "7", "15", "]", "expr", "(", "Q", "))", "True" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L603-L622
[ "def", "pl_fc_entails", "(", "KB", ",", "q", ")", ":", "count", "=", "dict", "(", "[", "(", "c", ",", "len", "(", "conjuncts", "(", "c", ".", "args", "[", "0", "]", ")", ")", ")", "for", "c", "in", "KB", ".", "clauses", "if", "c", ".", "op", "==", "'>>'", "]", ")", "inferred", "=", "DefaultDict", "(", "False", ")", "agenda", "=", "[", "s", "for", "s", "in", "KB", ".", "clauses", "if", "is_prop_symbol", "(", "s", ".", "op", ")", "]", "while", "agenda", ":", "p", "=", "agenda", ".", "pop", "(", ")", "if", "p", "==", "q", ":", "return", "True", "if", "not", "inferred", "[", "p", "]", ":", "inferred", "[", "p", "]", "=", "True", "for", "c", "in", "KB", ".", "clauses_with_premise", "(", "p", ")", ":", "count", "[", "c", "]", "-=", "1", "if", "count", "[", "c", "]", "==", "0", ":", "agenda", ".", "append", "(", "c", ".", "args", "[", "1", "]", ")", "return", "False" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
dpll_satisfiable
Check satisfiability of a propositional sentence. This differs from the book code in two ways: (1) it returns a model rather than True when it succeeds; this is more useful. (2) The function find_pure_symbol is passed a list of unknown clauses, rather than a list of all clauses and the model; this is more efficient. >>> ppsubst(dpll_satisfiable(A&~B)) {A: True, B: False} >>> dpll_satisfiable(P&~P) False
aima/logic.py
def dpll_satisfiable(s): """Check satisfiability of a propositional sentence. This differs from the book code in two ways: (1) it returns a model rather than True when it succeeds; this is more useful. (2) The function find_pure_symbol is passed a list of unknown clauses, rather than a list of all clauses and the model; this is more efficient. >>> ppsubst(dpll_satisfiable(A&~B)) {A: True, B: False} >>> dpll_satisfiable(P&~P) False """ clauses = conjuncts(to_cnf(s)) symbols = prop_symbols(s) return dpll(clauses, symbols, {})
def dpll_satisfiable(s): """Check satisfiability of a propositional sentence. This differs from the book code in two ways: (1) it returns a model rather than True when it succeeds; this is more useful. (2) The function find_pure_symbol is passed a list of unknown clauses, rather than a list of all clauses and the model; this is more efficient. >>> ppsubst(dpll_satisfiable(A&~B)) {A: True, B: False} >>> dpll_satisfiable(P&~P) False """ clauses = conjuncts(to_cnf(s)) symbols = prop_symbols(s) return dpll(clauses, symbols, {})
[ "Check", "satisfiability", "of", "a", "propositional", "sentence", ".", "This", "differs", "from", "the", "book", "code", "in", "two", "ways", ":", "(", "1", ")", "it", "returns", "a", "model", "rather", "than", "True", "when", "it", "succeeds", ";", "this", "is", "more", "useful", ".", "(", "2", ")", "The", "function", "find_pure_symbol", "is", "passed", "a", "list", "of", "unknown", "clauses", "rather", "than", "a", "list", "of", "all", "clauses", "and", "the", "model", ";", "this", "is", "more", "efficient", ".", ">>>", "ppsubst", "(", "dpll_satisfiable", "(", "A&~B", "))", "{", "A", ":", "True", "B", ":", "False", "}", ">>>", "dpll_satisfiable", "(", "P&~P", ")", "False" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L635-L648
[ "def", "dpll_satisfiable", "(", "s", ")", ":", "clauses", "=", "conjuncts", "(", "to_cnf", "(", "s", ")", ")", "symbols", "=", "prop_symbols", "(", "s", ")", "return", "dpll", "(", "clauses", ",", "symbols", ",", "{", "}", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
dpll
See if the clauses are true in a partial model.
aima/logic.py
def dpll(clauses, symbols, model): "See if the clauses are true in a partial model." unknown_clauses = [] ## clauses with an unknown truth value for c in clauses: val = pl_true(c, model) if val == False: return False if val != True: unknown_clauses.append(c) if not unknown_clauses: return model P, value = find_pure_symbol(symbols, unknown_clauses) if P: return dpll(clauses, removeall(P, symbols), extend(model, P, value)) P, value = find_unit_clause(clauses, model) if P: return dpll(clauses, removeall(P, symbols), extend(model, P, value)) P, symbols = symbols[0], symbols[1:] return (dpll(clauses, symbols, extend(model, P, True)) or dpll(clauses, symbols, extend(model, P, False)))
def dpll(clauses, symbols, model): "See if the clauses are true in a partial model." unknown_clauses = [] ## clauses with an unknown truth value for c in clauses: val = pl_true(c, model) if val == False: return False if val != True: unknown_clauses.append(c) if not unknown_clauses: return model P, value = find_pure_symbol(symbols, unknown_clauses) if P: return dpll(clauses, removeall(P, symbols), extend(model, P, value)) P, value = find_unit_clause(clauses, model) if P: return dpll(clauses, removeall(P, symbols), extend(model, P, value)) P, symbols = symbols[0], symbols[1:] return (dpll(clauses, symbols, extend(model, P, True)) or dpll(clauses, symbols, extend(model, P, False)))
[ "See", "if", "the", "clauses", "are", "true", "in", "a", "partial", "model", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L650-L669
[ "def", "dpll", "(", "clauses", ",", "symbols", ",", "model", ")", ":", "unknown_clauses", "=", "[", "]", "## clauses with an unknown truth value", "for", "c", "in", "clauses", ":", "val", "=", "pl_true", "(", "c", ",", "model", ")", "if", "val", "==", "False", ":", "return", "False", "if", "val", "!=", "True", ":", "unknown_clauses", ".", "append", "(", "c", ")", "if", "not", "unknown_clauses", ":", "return", "model", "P", ",", "value", "=", "find_pure_symbol", "(", "symbols", ",", "unknown_clauses", ")", "if", "P", ":", "return", "dpll", "(", "clauses", ",", "removeall", "(", "P", ",", "symbols", ")", ",", "extend", "(", "model", ",", "P", ",", "value", ")", ")", "P", ",", "value", "=", "find_unit_clause", "(", "clauses", ",", "model", ")", "if", "P", ":", "return", "dpll", "(", "clauses", ",", "removeall", "(", "P", ",", "symbols", ")", ",", "extend", "(", "model", ",", "P", ",", "value", ")", ")", "P", ",", "symbols", "=", "symbols", "[", "0", "]", ",", "symbols", "[", "1", ":", "]", "return", "(", "dpll", "(", "clauses", ",", "symbols", ",", "extend", "(", "model", ",", "P", ",", "True", ")", ")", "or", "dpll", "(", "clauses", ",", "symbols", ",", "extend", "(", "model", ",", "P", ",", "False", ")", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
find_pure_symbol
Find a symbol and its value if it appears only as a positive literal (or only as a negative) in clauses. >>> find_pure_symbol([A, B, C], [A|~B,~B|~C,C|A]) (A, True)
aima/logic.py
def find_pure_symbol(symbols, clauses): """Find a symbol and its value if it appears only as a positive literal (or only as a negative) in clauses. >>> find_pure_symbol([A, B, C], [A|~B,~B|~C,C|A]) (A, True) """ for s in symbols: found_pos, found_neg = False, False for c in clauses: if not found_pos and s in disjuncts(c): found_pos = True if not found_neg and ~s in disjuncts(c): found_neg = True if found_pos != found_neg: return s, found_pos return None, None
def find_pure_symbol(symbols, clauses): """Find a symbol and its value if it appears only as a positive literal (or only as a negative) in clauses. >>> find_pure_symbol([A, B, C], [A|~B,~B|~C,C|A]) (A, True) """ for s in symbols: found_pos, found_neg = False, False for c in clauses: if not found_pos and s in disjuncts(c): found_pos = True if not found_neg and ~s in disjuncts(c): found_neg = True if found_pos != found_neg: return s, found_pos return None, None
[ "Find", "a", "symbol", "and", "its", "value", "if", "it", "appears", "only", "as", "a", "positive", "literal", "(", "or", "only", "as", "a", "negative", ")", "in", "clauses", ".", ">>>", "find_pure_symbol", "(", "[", "A", "B", "C", "]", "[", "A|~B", "~B|~C", "C|A", "]", ")", "(", "A", "True", ")" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L671-L683
[ "def", "find_pure_symbol", "(", "symbols", ",", "clauses", ")", ":", "for", "s", "in", "symbols", ":", "found_pos", ",", "found_neg", "=", "False", ",", "False", "for", "c", "in", "clauses", ":", "if", "not", "found_pos", "and", "s", "in", "disjuncts", "(", "c", ")", ":", "found_pos", "=", "True", "if", "not", "found_neg", "and", "~", "s", "in", "disjuncts", "(", "c", ")", ":", "found_neg", "=", "True", "if", "found_pos", "!=", "found_neg", ":", "return", "s", ",", "found_pos", "return", "None", ",", "None" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
find_unit_clause
Find a forced assignment if possible from a clause with only 1 variable not bound in the model. >>> find_unit_clause([A|B|C, B|~C, ~A|~B], {A:True}) (B, False)
aima/logic.py
def find_unit_clause(clauses, model): """Find a forced assignment if possible from a clause with only 1 variable not bound in the model. >>> find_unit_clause([A|B|C, B|~C, ~A|~B], {A:True}) (B, False) """ for clause in clauses: P, value = unit_clause_assign(clause, model) if P: return P, value return None, None
def find_unit_clause(clauses, model): """Find a forced assignment if possible from a clause with only 1 variable not bound in the model. >>> find_unit_clause([A|B|C, B|~C, ~A|~B], {A:True}) (B, False) """ for clause in clauses: P, value = unit_clause_assign(clause, model) if P: return P, value return None, None
[ "Find", "a", "forced", "assignment", "if", "possible", "from", "a", "clause", "with", "only", "1", "variable", "not", "bound", "in", "the", "model", ".", ">>>", "find_unit_clause", "(", "[", "A|B|C", "B|~C", "~A|~B", "]", "{", "A", ":", "True", "}", ")", "(", "B", "False", ")" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L685-L694
[ "def", "find_unit_clause", "(", "clauses", ",", "model", ")", ":", "for", "clause", "in", "clauses", ":", "P", ",", "value", "=", "unit_clause_assign", "(", "clause", ",", "model", ")", "if", "P", ":", "return", "P", ",", "value", "return", "None", ",", "None" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
unit_clause_assign
Return a single variable/value pair that makes clause true in the model, if possible. >>> unit_clause_assign(A|B|C, {A:True}) (None, None) >>> unit_clause_assign(B|~C, {A:True}) (None, None) >>> unit_clause_assign(~A|~B, {A:True}) (B, False)
aima/logic.py
def unit_clause_assign(clause, model): """Return a single variable/value pair that makes clause true in the model, if possible. >>> unit_clause_assign(A|B|C, {A:True}) (None, None) >>> unit_clause_assign(B|~C, {A:True}) (None, None) >>> unit_clause_assign(~A|~B, {A:True}) (B, False) """ P, value = None, None for literal in disjuncts(clause): sym, positive = inspect_literal(literal) if sym in model: if model[sym] == positive: return None, None # clause already True elif P: return None, None # more than 1 unbound variable else: P, value = sym, positive return P, value
def unit_clause_assign(clause, model): """Return a single variable/value pair that makes clause true in the model, if possible. >>> unit_clause_assign(A|B|C, {A:True}) (None, None) >>> unit_clause_assign(B|~C, {A:True}) (None, None) >>> unit_clause_assign(~A|~B, {A:True}) (B, False) """ P, value = None, None for literal in disjuncts(clause): sym, positive = inspect_literal(literal) if sym in model: if model[sym] == positive: return None, None # clause already True elif P: return None, None # more than 1 unbound variable else: P, value = sym, positive return P, value
[ "Return", "a", "single", "variable", "/", "value", "pair", "that", "makes", "clause", "true", "in", "the", "model", "if", "possible", ".", ">>>", "unit_clause_assign", "(", "A|B|C", "{", "A", ":", "True", "}", ")", "(", "None", "None", ")", ">>>", "unit_clause_assign", "(", "B|~C", "{", "A", ":", "True", "}", ")", "(", "None", "None", ")", ">>>", "unit_clause_assign", "(", "~A|~B", "{", "A", ":", "True", "}", ")", "(", "B", "False", ")" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L696-L716
[ "def", "unit_clause_assign", "(", "clause", ",", "model", ")", ":", "P", ",", "value", "=", "None", ",", "None", "for", "literal", "in", "disjuncts", "(", "clause", ")", ":", "sym", ",", "positive", "=", "inspect_literal", "(", "literal", ")", "if", "sym", "in", "model", ":", "if", "model", "[", "sym", "]", "==", "positive", ":", "return", "None", ",", "None", "# clause already True", "elif", "P", ":", "return", "None", ",", "None", "# more than 1 unbound variable", "else", ":", "P", ",", "value", "=", "sym", ",", "positive", "return", "P", ",", "value" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
SAT_plan
[Fig. 7.22]
aima/logic.py
def SAT_plan(init, transition, goal, t_max, SAT_solver=dpll_satisfiable): "[Fig. 7.22]" for t in range(t_max): cnf = translate_to_SAT(init, transition, goal, t) model = SAT_solver(cnf) if model is not False: return extract_solution(model) return None
def SAT_plan(init, transition, goal, t_max, SAT_solver=dpll_satisfiable): "[Fig. 7.22]" for t in range(t_max): cnf = translate_to_SAT(init, transition, goal, t) model = SAT_solver(cnf) if model is not False: return extract_solution(model) return None
[ "[", "Fig", ".", "7", ".", "22", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L765-L772
[ "def", "SAT_plan", "(", "init", ",", "transition", ",", "goal", ",", "t_max", ",", "SAT_solver", "=", "dpll_satisfiable", ")", ":", "for", "t", "in", "range", "(", "t_max", ")", ":", "cnf", "=", "translate_to_SAT", "(", "init", ",", "transition", ",", "goal", ",", "t", ")", "model", "=", "SAT_solver", "(", "cnf", ")", "if", "model", "is", "not", "False", ":", "return", "extract_solution", "(", "model", ")", "return", "None" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
unify
Unify expressions x,y with substitution s; return a substitution that would make x,y equal, or None if x,y can not unify. x and y can be variables (e.g. Expr('x')), constants, lists, or Exprs. [Fig. 9.1] >>> ppsubst(unify(x + y, y + C, {})) {x: y, y: C}
aima/logic.py
def unify(x, y, s): """Unify expressions x,y with substitution s; return a substitution that would make x,y equal, or None if x,y can not unify. x and y can be variables (e.g. Expr('x')), constants, lists, or Exprs. [Fig. 9.1] >>> ppsubst(unify(x + y, y + C, {})) {x: y, y: C} """ if s is None: return None elif x == y: return s elif is_variable(x): return unify_var(x, y, s) elif is_variable(y): return unify_var(y, x, s) elif isinstance(x, Expr) and isinstance(y, Expr): return unify(x.args, y.args, unify(x.op, y.op, s)) elif isinstance(x, str) or isinstance(y, str): return None elif issequence(x) and issequence(y) and len(x) == len(y): if not x: return s return unify(x[1:], y[1:], unify(x[0], y[0], s)) else: return None
def unify(x, y, s): """Unify expressions x,y with substitution s; return a substitution that would make x,y equal, or None if x,y can not unify. x and y can be variables (e.g. Expr('x')), constants, lists, or Exprs. [Fig. 9.1] >>> ppsubst(unify(x + y, y + C, {})) {x: y, y: C} """ if s is None: return None elif x == y: return s elif is_variable(x): return unify_var(x, y, s) elif is_variable(y): return unify_var(y, x, s) elif isinstance(x, Expr) and isinstance(y, Expr): return unify(x.args, y.args, unify(x.op, y.op, s)) elif isinstance(x, str) or isinstance(y, str): return None elif issequence(x) and issequence(y) and len(x) == len(y): if not x: return s return unify(x[1:], y[1:], unify(x[0], y[0], s)) else: return None
[ "Unify", "expressions", "x", "y", "with", "substitution", "s", ";", "return", "a", "substitution", "that", "would", "make", "x", "y", "equal", "or", "None", "if", "x", "y", "can", "not", "unify", ".", "x", "and", "y", "can", "be", "variables", "(", "e", ".", "g", ".", "Expr", "(", "x", "))", "constants", "lists", "or", "Exprs", ".", "[", "Fig", ".", "9", ".", "1", "]", ">>>", "ppsubst", "(", "unify", "(", "x", "+", "y", "y", "+", "C", "{}", "))", "{", "x", ":", "y", "y", ":", "C", "}" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L782-L805
[ "def", "unify", "(", "x", ",", "y", ",", "s", ")", ":", "if", "s", "is", "None", ":", "return", "None", "elif", "x", "==", "y", ":", "return", "s", "elif", "is_variable", "(", "x", ")", ":", "return", "unify_var", "(", "x", ",", "y", ",", "s", ")", "elif", "is_variable", "(", "y", ")", ":", "return", "unify_var", "(", "y", ",", "x", ",", "s", ")", "elif", "isinstance", "(", "x", ",", "Expr", ")", "and", "isinstance", "(", "y", ",", "Expr", ")", ":", "return", "unify", "(", "x", ".", "args", ",", "y", ".", "args", ",", "unify", "(", "x", ".", "op", ",", "y", ".", "op", ",", "s", ")", ")", "elif", "isinstance", "(", "x", ",", "str", ")", "or", "isinstance", "(", "y", ",", "str", ")", ":", "return", "None", "elif", "issequence", "(", "x", ")", "and", "issequence", "(", "y", ")", "and", "len", "(", "x", ")", "==", "len", "(", "y", ")", ":", "if", "not", "x", ":", "return", "s", "return", "unify", "(", "x", "[", "1", ":", "]", ",", "y", "[", "1", ":", "]", ",", "unify", "(", "x", "[", "0", "]", ",", "y", "[", "0", "]", ",", "s", ")", ")", "else", ":", "return", "None" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
is_variable
A variable is an Expr with no args and a lowercase symbol as the op.
aima/logic.py
def is_variable(x): "A variable is an Expr with no args and a lowercase symbol as the op." return isinstance(x, Expr) and not x.args and is_var_symbol(x.op)
def is_variable(x): "A variable is an Expr with no args and a lowercase symbol as the op." return isinstance(x, Expr) and not x.args and is_var_symbol(x.op)
[ "A", "variable", "is", "an", "Expr", "with", "no", "args", "and", "a", "lowercase", "symbol", "as", "the", "op", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L807-L809
[ "def", "is_variable", "(", "x", ")", ":", "return", "isinstance", "(", "x", ",", "Expr", ")", "and", "not", "x", ".", "args", "and", "is_var_symbol", "(", "x", ".", "op", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
occur_check
Return true if variable var occurs anywhere in x (or in subst(s, x), if s has a binding for x).
aima/logic.py
def occur_check(var, x, s): """Return true if variable var occurs anywhere in x (or in subst(s, x), if s has a binding for x).""" if var == x: return True elif is_variable(x) and x in s: return occur_check(var, s[x], s) elif isinstance(x, Expr): return (occur_check(var, x.op, s) or occur_check(var, x.args, s)) elif isinstance(x, (list, tuple)): return some(lambda element: occur_check(var, element, s), x) else: return False
def occur_check(var, x, s): """Return true if variable var occurs anywhere in x (or in subst(s, x), if s has a binding for x).""" if var == x: return True elif is_variable(x) and x in s: return occur_check(var, s[x], s) elif isinstance(x, Expr): return (occur_check(var, x.op, s) or occur_check(var, x.args, s)) elif isinstance(x, (list, tuple)): return some(lambda element: occur_check(var, element, s), x) else: return False
[ "Return", "true", "if", "variable", "var", "occurs", "anywhere", "in", "x", "(", "or", "in", "subst", "(", "s", "x", ")", "if", "s", "has", "a", "binding", "for", "x", ")", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L819-L832
[ "def", "occur_check", "(", "var", ",", "x", ",", "s", ")", ":", "if", "var", "==", "x", ":", "return", "True", "elif", "is_variable", "(", "x", ")", "and", "x", "in", "s", ":", "return", "occur_check", "(", "var", ",", "s", "[", "x", "]", ",", "s", ")", "elif", "isinstance", "(", "x", ",", "Expr", ")", ":", "return", "(", "occur_check", "(", "var", ",", "x", ".", "op", ",", "s", ")", "or", "occur_check", "(", "var", ",", "x", ".", "args", ",", "s", ")", ")", "elif", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "some", "(", "lambda", "element", ":", "occur_check", "(", "var", ",", "element", ",", "s", ")", ",", "x", ")", "else", ":", "return", "False" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
extend
Copy the substitution s and extend it by setting var to val; return copy. >>> ppsubst(extend({x: 1}, y, 2)) {x: 1, y: 2}
aima/logic.py
def extend(s, var, val): """Copy the substitution s and extend it by setting var to val; return copy. >>> ppsubst(extend({x: 1}, y, 2)) {x: 1, y: 2} """ s2 = s.copy() s2[var] = val return s2
def extend(s, var, val): """Copy the substitution s and extend it by setting var to val; return copy. >>> ppsubst(extend({x: 1}, y, 2)) {x: 1, y: 2} """ s2 = s.copy() s2[var] = val return s2
[ "Copy", "the", "substitution", "s", "and", "extend", "it", "by", "setting", "var", "to", "val", ";", "return", "copy", ".", ">>>", "ppsubst", "(", "extend", "(", "{", "x", ":", "1", "}", "y", "2", "))", "{", "x", ":", "1", "y", ":", "2", "}" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L834-L842
[ "def", "extend", "(", "s", ",", "var", ",", "val", ")", ":", "s2", "=", "s", ".", "copy", "(", ")", "s2", "[", "var", "]", "=", "val", "return", "s2" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
subst
Substitute the substitution s into the expression x. >>> subst({x: 42, y:0}, F(x) + y) (F(42) + 0)
aima/logic.py
def subst(s, x): """Substitute the substitution s into the expression x. >>> subst({x: 42, y:0}, F(x) + y) (F(42) + 0) """ if isinstance(x, list): return [subst(s, xi) for xi in x] elif isinstance(x, tuple): return tuple([subst(s, xi) for xi in x]) elif not isinstance(x, Expr): return x elif is_var_symbol(x.op): return s.get(x, x) else: return Expr(x.op, *[subst(s, arg) for arg in x.args])
def subst(s, x): """Substitute the substitution s into the expression x. >>> subst({x: 42, y:0}, F(x) + y) (F(42) + 0) """ if isinstance(x, list): return [subst(s, xi) for xi in x] elif isinstance(x, tuple): return tuple([subst(s, xi) for xi in x]) elif not isinstance(x, Expr): return x elif is_var_symbol(x.op): return s.get(x, x) else: return Expr(x.op, *[subst(s, arg) for arg in x.args])
[ "Substitute", "the", "substitution", "s", "into", "the", "expression", "x", ".", ">>>", "subst", "(", "{", "x", ":", "42", "y", ":", "0", "}", "F", "(", "x", ")", "+", "y", ")", "(", "F", "(", "42", ")", "+", "0", ")" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L844-L858
[ "def", "subst", "(", "s", ",", "x", ")", ":", "if", "isinstance", "(", "x", ",", "list", ")", ":", "return", "[", "subst", "(", "s", ",", "xi", ")", "for", "xi", "in", "x", "]", "elif", "isinstance", "(", "x", ",", "tuple", ")", ":", "return", "tuple", "(", "[", "subst", "(", "s", ",", "xi", ")", "for", "xi", "in", "x", "]", ")", "elif", "not", "isinstance", "(", "x", ",", "Expr", ")", ":", "return", "x", "elif", "is_var_symbol", "(", "x", ".", "op", ")", ":", "return", "s", ".", "get", "(", "x", ",", "x", ")", "else", ":", "return", "Expr", "(", "x", ".", "op", ",", "*", "[", "subst", "(", "s", ",", "arg", ")", "for", "arg", "in", "x", ".", "args", "]", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
fol_fc_ask
Inefficient forward chaining for first-order logic. [Fig. 9.3] KB is a FolKB and alpha must be an atomic sentence.
aima/logic.py
def fol_fc_ask(KB, alpha): """Inefficient forward chaining for first-order logic. [Fig. 9.3] KB is a FolKB and alpha must be an atomic sentence.""" while True: new = {} for r in KB.clauses: ps, q = parse_definite_clause(standardize_variables(r)) raise NotImplementedError
def fol_fc_ask(KB, alpha): """Inefficient forward chaining for first-order logic. [Fig. 9.3] KB is a FolKB and alpha must be an atomic sentence.""" while True: new = {} for r in KB.clauses: ps, q = parse_definite_clause(standardize_variables(r)) raise NotImplementedError
[ "Inefficient", "forward", "chaining", "for", "first", "-", "order", "logic", ".", "[", "Fig", ".", "9", ".", "3", "]", "KB", "is", "a", "FolKB", "and", "alpha", "must", "be", "an", "atomic", "sentence", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L860-L867
[ "def", "fol_fc_ask", "(", "KB", ",", "alpha", ")", ":", "while", "True", ":", "new", "=", "{", "}", "for", "r", "in", "KB", ".", "clauses", ":", "ps", ",", "q", "=", "parse_definite_clause", "(", "standardize_variables", "(", "r", ")", ")", "raise", "NotImplementedError" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
standardize_variables
Replace all the variables in sentence with new variables. >>> e = expr('F(a, b, c) & G(c, A, 23)') >>> len(variables(standardize_variables(e))) 3 >>> variables(e).intersection(variables(standardize_variables(e))) set([]) >>> is_variable(standardize_variables(expr('x'))) True
aima/logic.py
def standardize_variables(sentence, dic=None): """Replace all the variables in sentence with new variables. >>> e = expr('F(a, b, c) & G(c, A, 23)') >>> len(variables(standardize_variables(e))) 3 >>> variables(e).intersection(variables(standardize_variables(e))) set([]) >>> is_variable(standardize_variables(expr('x'))) True """ if dic is None: dic = {} if not isinstance(sentence, Expr): return sentence elif is_var_symbol(sentence.op): if sentence in dic: return dic[sentence] else: v = Expr('v_%d' % standardize_variables.counter.next()) dic[sentence] = v return v else: return Expr(sentence.op, *[standardize_variables(a, dic) for a in sentence.args])
def standardize_variables(sentence, dic=None): """Replace all the variables in sentence with new variables. >>> e = expr('F(a, b, c) & G(c, A, 23)') >>> len(variables(standardize_variables(e))) 3 >>> variables(e).intersection(variables(standardize_variables(e))) set([]) >>> is_variable(standardize_variables(expr('x'))) True """ if dic is None: dic = {} if not isinstance(sentence, Expr): return sentence elif is_var_symbol(sentence.op): if sentence in dic: return dic[sentence] else: v = Expr('v_%d' % standardize_variables.counter.next()) dic[sentence] = v return v else: return Expr(sentence.op, *[standardize_variables(a, dic) for a in sentence.args])
[ "Replace", "all", "the", "variables", "in", "sentence", "with", "new", "variables", ".", ">>>", "e", "=", "expr", "(", "F", "(", "a", "b", "c", ")", "&", "G", "(", "c", "A", "23", ")", ")", ">>>", "len", "(", "variables", "(", "standardize_variables", "(", "e", ")))", "3", ">>>", "variables", "(", "e", ")", ".", "intersection", "(", "variables", "(", "standardize_variables", "(", "e", ")))", "set", "(", "[]", ")", ">>>", "is_variable", "(", "standardize_variables", "(", "expr", "(", "x", ")))", "True" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L869-L891
[ "def", "standardize_variables", "(", "sentence", ",", "dic", "=", "None", ")", ":", "if", "dic", "is", "None", ":", "dic", "=", "{", "}", "if", "not", "isinstance", "(", "sentence", ",", "Expr", ")", ":", "return", "sentence", "elif", "is_var_symbol", "(", "sentence", ".", "op", ")", ":", "if", "sentence", "in", "dic", ":", "return", "dic", "[", "sentence", "]", "else", ":", "v", "=", "Expr", "(", "'v_%d'", "%", "standardize_variables", ".", "counter", ".", "next", "(", ")", ")", "dic", "[", "sentence", "]", "=", "v", "return", "v", "else", ":", "return", "Expr", "(", "sentence", ".", "op", ",", "*", "[", "standardize_variables", "(", "a", ",", "dic", ")", "for", "a", "in", "sentence", ".", "args", "]", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
diff
Return the symbolic derivative, dy/dx, as an Expr. However, you probably want to simplify the results with simp. >>> diff(x * x, x) ((x * 1) + (x * 1)) >>> simp(diff(x * x, x)) (2 * x)
aima/logic.py
def diff(y, x): """Return the symbolic derivative, dy/dx, as an Expr. However, you probably want to simplify the results with simp. >>> diff(x * x, x) ((x * 1) + (x * 1)) >>> simp(diff(x * x, x)) (2 * x) """ if y == x: return ONE elif not y.args: return ZERO else: u, op, v = y.args[0], y.op, y.args[-1] if op == '+': return diff(u, x) + diff(v, x) elif op == '-' and len(args) == 1: return -diff(u, x) elif op == '-': return diff(u, x) - diff(v, x) elif op == '*': return u * diff(v, x) + v * diff(u, x) elif op == '/': return (v*diff(u, x) - u*diff(v, x)) / (v * v) elif op == '**' and isnumber(x.op): return (v * u ** (v - 1) * diff(u, x)) elif op == '**': return (v * u ** (v - 1) * diff(u, x) + u ** v * Expr('log')(u) * diff(v, x)) elif op == 'log': return diff(u, x) / u else: raise ValueError("Unknown op: %s in diff(%s, %s)" % (op, y, x))
def diff(y, x): """Return the symbolic derivative, dy/dx, as an Expr. However, you probably want to simplify the results with simp. >>> diff(x * x, x) ((x * 1) + (x * 1)) >>> simp(diff(x * x, x)) (2 * x) """ if y == x: return ONE elif not y.args: return ZERO else: u, op, v = y.args[0], y.op, y.args[-1] if op == '+': return diff(u, x) + diff(v, x) elif op == '-' and len(args) == 1: return -diff(u, x) elif op == '-': return diff(u, x) - diff(v, x) elif op == '*': return u * diff(v, x) + v * diff(u, x) elif op == '/': return (v*diff(u, x) - u*diff(v, x)) / (v * v) elif op == '**' and isnumber(x.op): return (v * u ** (v - 1) * diff(u, x)) elif op == '**': return (v * u ** (v - 1) * diff(u, x) + u ** v * Expr('log')(u) * diff(v, x)) elif op == 'log': return diff(u, x) / u else: raise ValueError("Unknown op: %s in diff(%s, %s)" % (op, y, x))
[ "Return", "the", "symbolic", "derivative", "dy", "/", "dx", "as", "an", "Expr", ".", "However", "you", "probably", "want", "to", "simplify", "the", "results", "with", "simp", ".", ">>>", "diff", "(", "x", "*", "x", "x", ")", "((", "x", "*", "1", ")", "+", "(", "x", "*", "1", "))", ">>>", "simp", "(", "diff", "(", "x", "*", "x", "x", "))", "(", "2", "*", "x", ")" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L1006-L1028
[ "def", "diff", "(", "y", ",", "x", ")", ":", "if", "y", "==", "x", ":", "return", "ONE", "elif", "not", "y", ".", "args", ":", "return", "ZERO", "else", ":", "u", ",", "op", ",", "v", "=", "y", ".", "args", "[", "0", "]", ",", "y", ".", "op", ",", "y", ".", "args", "[", "-", "1", "]", "if", "op", "==", "'+'", ":", "return", "diff", "(", "u", ",", "x", ")", "+", "diff", "(", "v", ",", "x", ")", "elif", "op", "==", "'-'", "and", "len", "(", "args", ")", "==", "1", ":", "return", "-", "diff", "(", "u", ",", "x", ")", "elif", "op", "==", "'-'", ":", "return", "diff", "(", "u", ",", "x", ")", "-", "diff", "(", "v", ",", "x", ")", "elif", "op", "==", "'*'", ":", "return", "u", "*", "diff", "(", "v", ",", "x", ")", "+", "v", "*", "diff", "(", "u", ",", "x", ")", "elif", "op", "==", "'/'", ":", "return", "(", "v", "*", "diff", "(", "u", ",", "x", ")", "-", "u", "*", "diff", "(", "v", ",", "x", ")", ")", "/", "(", "v", "*", "v", ")", "elif", "op", "==", "'**'", "and", "isnumber", "(", "x", ".", "op", ")", ":", "return", "(", "v", "*", "u", "**", "(", "v", "-", "1", ")", "*", "diff", "(", "u", ",", "x", ")", ")", "elif", "op", "==", "'**'", ":", "return", "(", "v", "*", "u", "**", "(", "v", "-", "1", ")", "*", "diff", "(", "u", ",", "x", ")", "+", "u", "**", "v", "*", "Expr", "(", "'log'", ")", "(", "u", ")", "*", "diff", "(", "v", ",", "x", ")", ")", "elif", "op", "==", "'log'", ":", "return", "diff", "(", "u", ",", "x", ")", "/", "u", "else", ":", "raise", "ValueError", "(", "\"Unknown op: %s in diff(%s, %s)\"", "%", "(", "op", ",", "y", ",", "x", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
pretty_dict
Return dictionary d's repr but with the items sorted. >>> pretty_dict({'m': 'M', 'a': 'A', 'r': 'R', 'k': 'K'}) "{'a': 'A', 'k': 'K', 'm': 'M', 'r': 'R'}" >>> pretty_dict({z: C, y: B, x: A}) '{x: A, y: B, z: C}'
aima/logic.py
def pretty_dict(d): """Return dictionary d's repr but with the items sorted. >>> pretty_dict({'m': 'M', 'a': 'A', 'r': 'R', 'k': 'K'}) "{'a': 'A', 'k': 'K', 'm': 'M', 'r': 'R'}" >>> pretty_dict({z: C, y: B, x: A}) '{x: A, y: B, z: C}' """ return '{%s}' % ', '.join('%r: %r' % (k, v) for k, v in sorted(d.items(), key=repr))
def pretty_dict(d): """Return dictionary d's repr but with the items sorted. >>> pretty_dict({'m': 'M', 'a': 'A', 'r': 'R', 'k': 'K'}) "{'a': 'A', 'k': 'K', 'm': 'M', 'r': 'R'}" >>> pretty_dict({z: C, y: B, x: A}) '{x: A, y: B, z: C}' """ return '{%s}' % ', '.join('%r: %r' % (k, v) for k, v in sorted(d.items(), key=repr))
[ "Return", "dictionary", "d", "s", "repr", "but", "with", "the", "items", "sorted", ".", ">>>", "pretty_dict", "(", "{", "m", ":", "M", "a", ":", "A", "r", ":", "R", "k", ":", "K", "}", ")", "{", "a", ":", "A", "k", ":", "K", "m", ":", "M", "r", ":", "R", "}", ">>>", "pretty_dict", "(", "{", "z", ":", "C", "y", ":", "B", "x", ":", "A", "}", ")", "{", "x", ":", "A", "y", ":", "B", "z", ":", "C", "}" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L1083-L1091
[ "def", "pretty_dict", "(", "d", ")", ":", "return", "'{%s}'", "%", "', '", ".", "join", "(", "'%r: %r'", "%", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "sorted", "(", "d", ".", "items", "(", ")", ",", "key", "=", "repr", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
PropKB.retract
Remove the sentence's clauses from the KB.
aima/logic.py
def retract(self, sentence): "Remove the sentence's clauses from the KB." for c in conjuncts(to_cnf(sentence)): if c in self.clauses: self.clauses.remove(c)
def retract(self, sentence): "Remove the sentence's clauses from the KB." for c in conjuncts(to_cnf(sentence)): if c in self.clauses: self.clauses.remove(c)
[ "Remove", "the", "sentence", "s", "clauses", "from", "the", "KB", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L84-L88
[ "def", "retract", "(", "self", ",", "sentence", ")", ":", "for", "c", "in", "conjuncts", "(", "to_cnf", "(", "sentence", ")", ")", ":", "if", "c", "in", "self", ".", "clauses", ":", "self", ".", "clauses", ".", "remove", "(", "c", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
PropDefiniteKB.clauses_with_premise
Return a list of the clauses in KB that have p in their premise. This could be cached away for O(1) speed, but we'll recompute it.
aima/logic.py
def clauses_with_premise(self, p): """Return a list of the clauses in KB that have p in their premise. This could be cached away for O(1) speed, but we'll recompute it.""" return [c for c in self.clauses if c.op == '>>' and p in conjuncts(c.args[0])]
def clauses_with_premise(self, p): """Return a list of the clauses in KB that have p in their premise. This could be cached away for O(1) speed, but we'll recompute it.""" return [c for c in self.clauses if c.op == '>>' and p in conjuncts(c.args[0])]
[ "Return", "a", "list", "of", "the", "clauses", "in", "KB", "that", "have", "p", "in", "their", "premise", ".", "This", "could", "be", "cached", "away", "for", "O", "(", "1", ")", "speed", "but", "we", "ll", "recompute", "it", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L597-L601
[ "def", "clauses_with_premise", "(", "self", ",", "p", ")", ":", "return", "[", "c", "for", "c", "in", "self", ".", "clauses", "if", "c", ".", "op", "==", "'>>'", "and", "p", "in", "conjuncts", "(", "c", ".", "args", "[", "0", "]", ")", "]" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
SettingDict.refresh
Updates the cache with setting values from the database.
model_settings/utils.py
def refresh(self): """ Updates the cache with setting values from the database. """ # `values_list('name', 'value')` doesn't work because `value` is not a # setting (base class) field, it's a setting value (subclass) field. So # we have to get real instances. args = [(obj.name, obj.value) for obj in self.queryset.all()] super(SettingDict, self).update(args) self.empty_cache = False
def refresh(self): """ Updates the cache with setting values from the database. """ # `values_list('name', 'value')` doesn't work because `value` is not a # setting (base class) field, it's a setting value (subclass) field. So # we have to get real instances. args = [(obj.name, obj.value) for obj in self.queryset.all()] super(SettingDict, self).update(args) self.empty_cache = False
[ "Updates", "the", "cache", "with", "setting", "values", "from", "the", "database", "." ]
ixc/django-model-settings
python
https://github.com/ixc/django-model-settings/blob/654233bf7f13619e4531741f9158e7034eac031b/model_settings/utils.py#L103-L112
[ "def", "refresh", "(", "self", ")", ":", "# `values_list('name', 'value')` doesn't work because `value` is not a", "# setting (base class) field, it's a setting value (subclass) field. So", "# we have to get real instances.", "args", "=", "[", "(", "obj", ".", "name", ",", "obj", ".", "value", ")", "for", "obj", "in", "self", ".", "queryset", ".", "all", "(", ")", "]", "super", "(", "SettingDict", ",", "self", ")", ".", "update", "(", "args", ")", "self", ".", "empty_cache", "=", "False" ]
654233bf7f13619e4531741f9158e7034eac031b
valid
minimax_decision
Given a state in a game, calculate the best move by searching forward all the way to the terminal states. [Fig. 5.3]
aima/games.py
def minimax_decision(state, game): """Given a state in a game, calculate the best move by searching forward all the way to the terminal states. [Fig. 5.3]""" player = game.to_move(state) def max_value(state): if game.terminal_test(state): return game.utility(state, player) v = -infinity for a in game.actions(state): v = max(v, min_value(game.result(state, a))) return v def min_value(state): if game.terminal_test(state): return game.utility(state, player) v = infinity for a in game.actions(state): v = min(v, max_value(game.result(state, a))) return v # Body of minimax_decision: return argmax(game.actions(state), lambda a: min_value(game.result(state, a)))
def minimax_decision(state, game): """Given a state in a game, calculate the best move by searching forward all the way to the terminal states. [Fig. 5.3]""" player = game.to_move(state) def max_value(state): if game.terminal_test(state): return game.utility(state, player) v = -infinity for a in game.actions(state): v = max(v, min_value(game.result(state, a))) return v def min_value(state): if game.terminal_test(state): return game.utility(state, player) v = infinity for a in game.actions(state): v = min(v, max_value(game.result(state, a))) return v # Body of minimax_decision: return argmax(game.actions(state), lambda a: min_value(game.result(state, a)))
[ "Given", "a", "state", "in", "a", "game", "calculate", "the", "best", "move", "by", "searching", "forward", "all", "the", "way", "to", "the", "terminal", "states", ".", "[", "Fig", ".", "5", ".", "3", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/games.py#L10-L34
[ "def", "minimax_decision", "(", "state", ",", "game", ")", ":", "player", "=", "game", ".", "to_move", "(", "state", ")", "def", "max_value", "(", "state", ")", ":", "if", "game", ".", "terminal_test", "(", "state", ")", ":", "return", "game", ".", "utility", "(", "state", ",", "player", ")", "v", "=", "-", "infinity", "for", "a", "in", "game", ".", "actions", "(", "state", ")", ":", "v", "=", "max", "(", "v", ",", "min_value", "(", "game", ".", "result", "(", "state", ",", "a", ")", ")", ")", "return", "v", "def", "min_value", "(", "state", ")", ":", "if", "game", ".", "terminal_test", "(", "state", ")", ":", "return", "game", ".", "utility", "(", "state", ",", "player", ")", "v", "=", "infinity", "for", "a", "in", "game", ".", "actions", "(", "state", ")", ":", "v", "=", "min", "(", "v", ",", "max_value", "(", "game", ".", "result", "(", "state", ",", "a", ")", ")", ")", "return", "v", "# Body of minimax_decision:", "return", "argmax", "(", "game", ".", "actions", "(", "state", ")", ",", "lambda", "a", ":", "min_value", "(", "game", ".", "result", "(", "state", ",", "a", ")", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
alphabeta_search
Search game to determine best action; use alpha-beta pruning. This version cuts off search and uses an evaluation function.
aima/games.py
def alphabeta_search(state, game, d=4, cutoff_test=None, eval_fn=None): """Search game to determine best action; use alpha-beta pruning. This version cuts off search and uses an evaluation function.""" player = game.to_move(state) def max_value(state, alpha, beta, depth): if cutoff_test(state, depth): return eval_fn(state) v = -infinity for a in game.actions(state): v = max(v, min_value(game.result(state, a), alpha, beta, depth+1)) if v >= beta: return v alpha = max(alpha, v) return v def min_value(state, alpha, beta, depth): if cutoff_test(state, depth): return eval_fn(state) v = infinity for a in game.actions(state): v = min(v, max_value(game.result(state, a), alpha, beta, depth+1)) if v <= alpha: return v beta = min(beta, v) return v # Body of alphabeta_search starts here: # The default test cuts off at depth d or at a terminal state cutoff_test = (cutoff_test or (lambda state,depth: depth>d or game.terminal_test(state))) eval_fn = eval_fn or (lambda state: game.utility(state, player)) return argmax(game.actions(state), lambda a: min_value(game.result(state, a), -infinity, infinity, 0))
def alphabeta_search(state, game, d=4, cutoff_test=None, eval_fn=None): """Search game to determine best action; use alpha-beta pruning. This version cuts off search and uses an evaluation function.""" player = game.to_move(state) def max_value(state, alpha, beta, depth): if cutoff_test(state, depth): return eval_fn(state) v = -infinity for a in game.actions(state): v = max(v, min_value(game.result(state, a), alpha, beta, depth+1)) if v >= beta: return v alpha = max(alpha, v) return v def min_value(state, alpha, beta, depth): if cutoff_test(state, depth): return eval_fn(state) v = infinity for a in game.actions(state): v = min(v, max_value(game.result(state, a), alpha, beta, depth+1)) if v <= alpha: return v beta = min(beta, v) return v # Body of alphabeta_search starts here: # The default test cuts off at depth d or at a terminal state cutoff_test = (cutoff_test or (lambda state,depth: depth>d or game.terminal_test(state))) eval_fn = eval_fn or (lambda state: game.utility(state, player)) return argmax(game.actions(state), lambda a: min_value(game.result(state, a), -infinity, infinity, 0))
[ "Search", "game", "to", "determine", "best", "action", ";", "use", "alpha", "-", "beta", "pruning", ".", "This", "version", "cuts", "off", "search", "and", "uses", "an", "evaluation", "function", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/games.py#L71-L108
[ "def", "alphabeta_search", "(", "state", ",", "game", ",", "d", "=", "4", ",", "cutoff_test", "=", "None", ",", "eval_fn", "=", "None", ")", ":", "player", "=", "game", ".", "to_move", "(", "state", ")", "def", "max_value", "(", "state", ",", "alpha", ",", "beta", ",", "depth", ")", ":", "if", "cutoff_test", "(", "state", ",", "depth", ")", ":", "return", "eval_fn", "(", "state", ")", "v", "=", "-", "infinity", "for", "a", "in", "game", ".", "actions", "(", "state", ")", ":", "v", "=", "max", "(", "v", ",", "min_value", "(", "game", ".", "result", "(", "state", ",", "a", ")", ",", "alpha", ",", "beta", ",", "depth", "+", "1", ")", ")", "if", "v", ">=", "beta", ":", "return", "v", "alpha", "=", "max", "(", "alpha", ",", "v", ")", "return", "v", "def", "min_value", "(", "state", ",", "alpha", ",", "beta", ",", "depth", ")", ":", "if", "cutoff_test", "(", "state", ",", "depth", ")", ":", "return", "eval_fn", "(", "state", ")", "v", "=", "infinity", "for", "a", "in", "game", ".", "actions", "(", "state", ")", ":", "v", "=", "min", "(", "v", ",", "max_value", "(", "game", ".", "result", "(", "state", ",", "a", ")", ",", "alpha", ",", "beta", ",", "depth", "+", "1", ")", ")", "if", "v", "<=", "alpha", ":", "return", "v", "beta", "=", "min", "(", "beta", ",", "v", ")", "return", "v", "# Body of alphabeta_search starts here:", "# The default test cuts off at depth d or at a terminal state", "cutoff_test", "=", "(", "cutoff_test", "or", "(", "lambda", "state", ",", "depth", ":", "depth", ">", "d", "or", "game", ".", "terminal_test", "(", "state", ")", ")", ")", "eval_fn", "=", "eval_fn", "or", "(", "lambda", "state", ":", "game", ".", "utility", "(", "state", ",", "player", ")", ")", "return", "argmax", "(", "game", ".", "actions", "(", "state", ")", ",", "lambda", "a", ":", "min_value", "(", "game", ".", "result", "(", "state", ",", "a", ")", ",", "-", "infinity", ",", "infinity", ",", "0", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
play_game
Play an n-person, move-alternating game. >>> play_game(Fig52Game(), alphabeta_player, alphabeta_player) 3
aima/games.py
def play_game(game, *players): """Play an n-person, move-alternating game. >>> play_game(Fig52Game(), alphabeta_player, alphabeta_player) 3 """ state = game.initial while True: for player in players: move = player(game, state) state = game.result(state, move) if game.terminal_test(state): return game.utility(state, game.to_move(game.initial))
def play_game(game, *players): """Play an n-person, move-alternating game. >>> play_game(Fig52Game(), alphabeta_player, alphabeta_player) 3 """ state = game.initial while True: for player in players: move = player(game, state) state = game.result(state, move) if game.terminal_test(state): return game.utility(state, game.to_move(game.initial))
[ "Play", "an", "n", "-", "person", "move", "-", "alternating", "game", ".", ">>>", "play_game", "(", "Fig52Game", "()", "alphabeta_player", "alphabeta_player", ")", "3" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/games.py#L125-L136
[ "def", "play_game", "(", "game", ",", "*", "players", ")", ":", "state", "=", "game", ".", "initial", "while", "True", ":", "for", "player", "in", "players", ":", "move", "=", "player", "(", "game", ",", "state", ")", "state", "=", "game", ".", "result", "(", "state", ",", "move", ")", "if", "game", ".", "terminal_test", "(", "state", ")", ":", "return", "game", ".", "utility", "(", "state", ",", "game", ".", "to_move", "(", "game", ".", "initial", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
TicTacToe.utility
Return the value to player; 1 for win, -1 for loss, 0 otherwise.
aima/games.py
def utility(self, state, player): "Return the value to player; 1 for win, -1 for loss, 0 otherwise." return if_(player == 'X', state.utility, -state.utility)
def utility(self, state, player): "Return the value to player; 1 for win, -1 for loss, 0 otherwise." return if_(player == 'X', state.utility, -state.utility)
[ "Return", "the", "value", "to", "player", ";", "1", "for", "win", "-", "1", "for", "loss", "0", "otherwise", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/games.py#L236-L238
[ "def", "utility", "(", "self", ",", "state", ",", "player", ")", ":", "return", "if_", "(", "player", "==", "'X'", ",", "state", ".", "utility", ",", "-", "state", ".", "utility", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
TicTacToe.compute_utility
If X wins with this move, return 1; if O return -1; else return 0.
aima/games.py
def compute_utility(self, board, move, player): "If X wins with this move, return 1; if O return -1; else return 0." if (self.k_in_row(board, move, player, (0, 1)) or self.k_in_row(board, move, player, (1, 0)) or self.k_in_row(board, move, player, (1, -1)) or self.k_in_row(board, move, player, (1, 1))): return if_(player == 'X', +1, -1) else: return 0
def compute_utility(self, board, move, player): "If X wins with this move, return 1; if O return -1; else return 0." if (self.k_in_row(board, move, player, (0, 1)) or self.k_in_row(board, move, player, (1, 0)) or self.k_in_row(board, move, player, (1, -1)) or self.k_in_row(board, move, player, (1, 1))): return if_(player == 'X', +1, -1) else: return 0
[ "If", "X", "wins", "with", "this", "move", "return", "1", ";", "if", "O", "return", "-", "1", ";", "else", "return", "0", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/games.py#L251-L259
[ "def", "compute_utility", "(", "self", ",", "board", ",", "move", ",", "player", ")", ":", "if", "(", "self", ".", "k_in_row", "(", "board", ",", "move", ",", "player", ",", "(", "0", ",", "1", ")", ")", "or", "self", ".", "k_in_row", "(", "board", ",", "move", ",", "player", ",", "(", "1", ",", "0", ")", ")", "or", "self", ".", "k_in_row", "(", "board", ",", "move", ",", "player", ",", "(", "1", ",", "-", "1", ")", ")", "or", "self", ".", "k_in_row", "(", "board", ",", "move", ",", "player", ",", "(", "1", ",", "1", ")", ")", ")", ":", "return", "if_", "(", "player", "==", "'X'", ",", "+", "1", ",", "-", "1", ")", "else", ":", "return", "0" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
TicTacToe.k_in_row
Return true if there is a line through move on board for player.
aima/games.py
def k_in_row(self, board, move, player, (delta_x, delta_y)): "Return true if there is a line through move on board for player." x, y = move n = 0 # n is number of moves in row while board.get((x, y)) == player: n += 1 x, y = x + delta_x, y + delta_y x, y = move while board.get((x, y)) == player: n += 1 x, y = x - delta_x, y - delta_y n -= 1 # Because we counted move itself twice return n >= self.k
def k_in_row(self, board, move, player, (delta_x, delta_y)): "Return true if there is a line through move on board for player." x, y = move n = 0 # n is number of moves in row while board.get((x, y)) == player: n += 1 x, y = x + delta_x, y + delta_y x, y = move while board.get((x, y)) == player: n += 1 x, y = x - delta_x, y - delta_y n -= 1 # Because we counted move itself twice return n >= self.k
[ "Return", "true", "if", "there", "is", "a", "line", "through", "move", "on", "board", "for", "player", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/games.py#L261-L273
[ "def", "k_in_row", "(", "self", ",", "board", ",", "move", ",", "player", ",", "(", "delta_x", ",", "delta_y", ")", ")", ":", "x", ",", "y", "=", "move", "n", "=", "0", "# n is number of moves in row", "while", "board", ".", "get", "(", "(", "x", ",", "y", ")", ")", "==", "player", ":", "n", "+=", "1", "x", ",", "y", "=", "x", "+", "delta_x", ",", "y", "+", "delta_y", "x", ",", "y", "=", "move", "while", "board", ".", "get", "(", "(", "x", ",", "y", ")", ")", "==", "player", ":", "n", "+=", "1", "x", ",", "y", "=", "x", "-", "delta_x", ",", "y", "-", "delta_y", "n", "-=", "1", "# Because we counted move itself twice", "return", "n", ">=", "self", ".", "k" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
update
Update a dict, or an object with slots, according to `entries` dict. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20)
aima/utils.py
def update(x, **entries): """Update a dict, or an object with slots, according to `entries` dict. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20) """ if isinstance(x, dict): x.update(entries) else: x.__dict__.update(entries) return x
def update(x, **entries): """Update a dict, or an object with slots, according to `entries` dict. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20) """ if isinstance(x, dict): x.update(entries) else: x.__dict__.update(entries) return x
[ "Update", "a", "dict", "or", "an", "object", "with", "slots", "according", "to", "entries", "dict", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L267-L279
[ "def", "update", "(", "x", ",", "*", "*", "entries", ")", ":", "if", "isinstance", "(", "x", ",", "dict", ")", ":", "x", ".", "update", "(", "entries", ")", "else", ":", "x", ".", "__dict__", ".", "update", "(", "entries", ")", "return", "x" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
removeall
Return a copy of seq (or string) with all occurences of item removed. >>> removeall(3, [1, 2, 3, 3, 2, 1, 3]) [1, 2, 2, 1] >>> removeall(4, [1, 2, 3]) [1, 2, 3]
aima/utils.py
def removeall(item, seq): """Return a copy of seq (or string) with all occurences of item removed. >>> removeall(3, [1, 2, 3, 3, 2, 1, 3]) [1, 2, 2, 1] >>> removeall(4, [1, 2, 3]) [1, 2, 3] """ if isinstance(seq, str): return seq.replace(item, '') else: return [x for x in seq if x != item]
def removeall(item, seq): """Return a copy of seq (or string) with all occurences of item removed. >>> removeall(3, [1, 2, 3, 3, 2, 1, 3]) [1, 2, 2, 1] >>> removeall(4, [1, 2, 3]) [1, 2, 3] """ if isinstance(seq, str): return seq.replace(item, '') else: return [x for x in seq if x != item]
[ "Return", "a", "copy", "of", "seq", "(", "or", "string", ")", "with", "all", "occurences", "of", "item", "removed", ".", ">>>", "removeall", "(", "3", "[", "1", "2", "3", "3", "2", "1", "3", "]", ")", "[", "1", "2", "2", "1", "]", ">>>", "removeall", "(", "4", "[", "1", "2", "3", "]", ")", "[", "1", "2", "3", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L286-L296
[ "def", "removeall", "(", "item", ",", "seq", ")", ":", "if", "isinstance", "(", "seq", ",", "str", ")", ":", "return", "seq", ".", "replace", "(", "item", ",", "''", ")", "else", ":", "return", "[", "x", "for", "x", "in", "seq", "if", "x", "!=", "item", "]" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
count_if
Count the number of elements of seq for which the predicate is true. >>> count_if(callable, [42, None, max, min]) 2
aima/utils.py
def count_if(predicate, seq): """Count the number of elements of seq for which the predicate is true. >>> count_if(callable, [42, None, max, min]) 2 """ f = lambda count, x: count + (not not predicate(x)) return reduce(f, seq, 0)
def count_if(predicate, seq): """Count the number of elements of seq for which the predicate is true. >>> count_if(callable, [42, None, max, min]) 2 """ f = lambda count, x: count + (not not predicate(x)) return reduce(f, seq, 0)
[ "Count", "the", "number", "of", "elements", "of", "seq", "for", "which", "the", "predicate", "is", "true", ".", ">>>", "count_if", "(", "callable", "[", "42", "None", "max", "min", "]", ")", "2" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L312-L318
[ "def", "count_if", "(", "predicate", ",", "seq", ")", ":", "f", "=", "lambda", "count", ",", "x", ":", "count", "+", "(", "not", "not", "predicate", "(", "x", ")", ")", "return", "reduce", "(", "f", ",", "seq", ",", "0", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
some
If some element x of seq satisfies predicate(x), return predicate(x). >>> some(callable, [min, 3]) 1 >>> some(callable, [2, 3]) 0
aima/utils.py
def some(predicate, seq): """If some element x of seq satisfies predicate(x), return predicate(x). >>> some(callable, [min, 3]) 1 >>> some(callable, [2, 3]) 0 """ for x in seq: px = predicate(x) if px: return px return False
def some(predicate, seq): """If some element x of seq satisfies predicate(x), return predicate(x). >>> some(callable, [min, 3]) 1 >>> some(callable, [2, 3]) 0 """ for x in seq: px = predicate(x) if px: return px return False
[ "If", "some", "element", "x", "of", "seq", "satisfies", "predicate", "(", "x", ")", "return", "predicate", "(", "x", ")", ".", ">>>", "some", "(", "callable", "[", "min", "3", "]", ")", "1", ">>>", "some", "(", "callable", "[", "2", "3", "]", ")", "0" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L341-L351
[ "def", "some", "(", "predicate", ",", "seq", ")", ":", "for", "x", "in", "seq", ":", "px", "=", "predicate", "(", "x", ")", "if", "px", ":", "return", "px", "return", "False" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
argmin
Return an element with lowest fn(seq[i]) score; tie goes to first one. >>> argmin(['one', 'to', 'three'], len) 'to'
aima/utils.py
def argmin(seq, fn): """Return an element with lowest fn(seq[i]) score; tie goes to first one. >>> argmin(['one', 'to', 'three'], len) 'to' """ best = seq[0]; best_score = fn(best) for x in seq: x_score = fn(x) if x_score < best_score: best, best_score = x, x_score return best
def argmin(seq, fn): """Return an element with lowest fn(seq[i]) score; tie goes to first one. >>> argmin(['one', 'to', 'three'], len) 'to' """ best = seq[0]; best_score = fn(best) for x in seq: x_score = fn(x) if x_score < best_score: best, best_score = x, x_score return best
[ "Return", "an", "element", "with", "lowest", "fn", "(", "seq", "[", "i", "]", ")", "score", ";", "tie", "goes", "to", "first", "one", ".", ">>>", "argmin", "(", "[", "one", "to", "three", "]", "len", ")", "to" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L372-L382
[ "def", "argmin", "(", "seq", ",", "fn", ")", ":", "best", "=", "seq", "[", "0", "]", "best_score", "=", "fn", "(", "best", ")", "for", "x", "in", "seq", ":", "x_score", "=", "fn", "(", "x", ")", "if", "x_score", "<", "best_score", ":", "best", ",", "best_score", "=", "x", ",", "x_score", "return", "best" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
argmin_list
Return a list of elements of seq[i] with the lowest fn(seq[i]) scores. >>> argmin_list(['one', 'to', 'three', 'or'], len) ['to', 'or']
aima/utils.py
def argmin_list(seq, fn): """Return a list of elements of seq[i] with the lowest fn(seq[i]) scores. >>> argmin_list(['one', 'to', 'three', 'or'], len) ['to', 'or'] """ best_score, best = fn(seq[0]), [] for x in seq: x_score = fn(x) if x_score < best_score: best, best_score = [x], x_score elif x_score == best_score: best.append(x) return best
def argmin_list(seq, fn): """Return a list of elements of seq[i] with the lowest fn(seq[i]) scores. >>> argmin_list(['one', 'to', 'three', 'or'], len) ['to', 'or'] """ best_score, best = fn(seq[0]), [] for x in seq: x_score = fn(x) if x_score < best_score: best, best_score = [x], x_score elif x_score == best_score: best.append(x) return best
[ "Return", "a", "list", "of", "elements", "of", "seq", "[", "i", "]", "with", "the", "lowest", "fn", "(", "seq", "[", "i", "]", ")", "scores", ".", ">>>", "argmin_list", "(", "[", "one", "to", "three", "or", "]", "len", ")", "[", "to", "or", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L384-L396
[ "def", "argmin_list", "(", "seq", ",", "fn", ")", ":", "best_score", ",", "best", "=", "fn", "(", "seq", "[", "0", "]", ")", ",", "[", "]", "for", "x", "in", "seq", ":", "x_score", "=", "fn", "(", "x", ")", "if", "x_score", "<", "best_score", ":", "best", ",", "best_score", "=", "[", "x", "]", ",", "x_score", "elif", "x_score", "==", "best_score", ":", "best", ".", "append", "(", "x", ")", "return", "best" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
argmin_random_tie
Return an element with lowest fn(seq[i]) score; break ties at random. Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)
aima/utils.py
def argmin_random_tie(seq, fn): """Return an element with lowest fn(seq[i]) score; break ties at random. Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)""" best_score = fn(seq[0]); n = 0 for x in seq: x_score = fn(x) if x_score < best_score: best, best_score = x, x_score; n = 1 elif x_score == best_score: n += 1 if random.randrange(n) == 0: best = x return best
def argmin_random_tie(seq, fn): """Return an element with lowest fn(seq[i]) score; break ties at random. Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)""" best_score = fn(seq[0]); n = 0 for x in seq: x_score = fn(x) if x_score < best_score: best, best_score = x, x_score; n = 1 elif x_score == best_score: n += 1 if random.randrange(n) == 0: best = x return best
[ "Return", "an", "element", "with", "lowest", "fn", "(", "seq", "[", "i", "]", ")", "score", ";", "break", "ties", "at", "random", ".", "Thus", "for", "all", "s", "f", ":", "argmin_random_tie", "(", "s", "f", ")", "in", "argmin_list", "(", "s", "f", ")" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L398-L410
[ "def", "argmin_random_tie", "(", "seq", ",", "fn", ")", ":", "best_score", "=", "fn", "(", "seq", "[", "0", "]", ")", "n", "=", "0", "for", "x", "in", "seq", ":", "x_score", "=", "fn", "(", "x", ")", "if", "x_score", "<", "best_score", ":", "best", ",", "best_score", "=", "x", ",", "x_score", "n", "=", "1", "elif", "x_score", "==", "best_score", ":", "n", "+=", "1", "if", "random", ".", "randrange", "(", "n", ")", "==", "0", ":", "best", "=", "x", "return", "best" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
histogram
Return a list of (value, count) pairs, summarizing the input values. Sorted by increasing value, or if mode=1, by decreasing count. If bin_function is given, map it over values first.
aima/utils.py
def histogram(values, mode=0, bin_function=None): """Return a list of (value, count) pairs, summarizing the input values. Sorted by increasing value, or if mode=1, by decreasing count. If bin_function is given, map it over values first.""" if bin_function: values = map(bin_function, values) bins = {} for val in values: bins[val] = bins.get(val, 0) + 1 if mode: return sorted(bins.items(), key=lambda x: (x[1],x[0]), reverse=True) else: return sorted(bins.items())
def histogram(values, mode=0, bin_function=None): """Return a list of (value, count) pairs, summarizing the input values. Sorted by increasing value, or if mode=1, by decreasing count. If bin_function is given, map it over values first.""" if bin_function: values = map(bin_function, values) bins = {} for val in values: bins[val] = bins.get(val, 0) + 1 if mode: return sorted(bins.items(), key=lambda x: (x[1],x[0]), reverse=True) else: return sorted(bins.items())
[ "Return", "a", "list", "of", "(", "value", "count", ")", "pairs", "summarizing", "the", "input", "values", ".", "Sorted", "by", "increasing", "value", "or", "if", "mode", "=", "1", "by", "decreasing", "count", ".", "If", "bin_function", "is", "given", "map", "it", "over", "values", "first", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L432-L443
[ "def", "histogram", "(", "values", ",", "mode", "=", "0", ",", "bin_function", "=", "None", ")", ":", "if", "bin_function", ":", "values", "=", "map", "(", "bin_function", ",", "values", ")", "bins", "=", "{", "}", "for", "val", "in", "values", ":", "bins", "[", "val", "]", "=", "bins", ".", "get", "(", "val", ",", "0", ")", "+", "1", "if", "mode", ":", "return", "sorted", "(", "bins", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "(", "x", "[", "1", "]", ",", "x", "[", "0", "]", ")", ",", "reverse", "=", "True", ")", "else", ":", "return", "sorted", "(", "bins", ".", "items", "(", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
median
Return the middle value, when the values are sorted. If there are an odd number of elements, try to average the middle two. If they can't be averaged (e.g. they are strings), choose one at random. >>> median([10, 100, 11]) 11 >>> median([1, 2, 3, 4]) 2.5
aima/utils.py
def median(values): """Return the middle value, when the values are sorted. If there are an odd number of elements, try to average the middle two. If they can't be averaged (e.g. they are strings), choose one at random. >>> median([10, 100, 11]) 11 >>> median([1, 2, 3, 4]) 2.5 """ n = len(values) values = sorted(values) if n % 2 == 1: return values[n/2] else: middle2 = values[(n/2)-1:(n/2)+1] try: return mean(middle2) except TypeError: return random.choice(middle2)
def median(values): """Return the middle value, when the values are sorted. If there are an odd number of elements, try to average the middle two. If they can't be averaged (e.g. they are strings), choose one at random. >>> median([10, 100, 11]) 11 >>> median([1, 2, 3, 4]) 2.5 """ n = len(values) values = sorted(values) if n % 2 == 1: return values[n/2] else: middle2 = values[(n/2)-1:(n/2)+1] try: return mean(middle2) except TypeError: return random.choice(middle2)
[ "Return", "the", "middle", "value", "when", "the", "values", "are", "sorted", ".", "If", "there", "are", "an", "odd", "number", "of", "elements", "try", "to", "average", "the", "middle", "two", ".", "If", "they", "can", "t", "be", "averaged", "(", "e", ".", "g", ".", "they", "are", "strings", ")", "choose", "one", "at", "random", ".", ">>>", "median", "(", "[", "10", "100", "11", "]", ")", "11", ">>>", "median", "(", "[", "1", "2", "3", "4", "]", ")", "2", ".", "5" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L459-L477
[ "def", "median", "(", "values", ")", ":", "n", "=", "len", "(", "values", ")", "values", "=", "sorted", "(", "values", ")", "if", "n", "%", "2", "==", "1", ":", "return", "values", "[", "n", "/", "2", "]", "else", ":", "middle2", "=", "values", "[", "(", "n", "/", "2", ")", "-", "1", ":", "(", "n", "/", "2", ")", "+", "1", "]", "try", ":", "return", "mean", "(", "middle2", ")", "except", "TypeError", ":", "return", "random", ".", "choice", "(", "middle2", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
dotproduct
Return the sum of the element-wise product of vectors x and y. >>> dotproduct([1, 2, 3], [1000, 100, 10]) 1230
aima/utils.py
def dotproduct(X, Y): """Return the sum of the element-wise product of vectors x and y. >>> dotproduct([1, 2, 3], [1000, 100, 10]) 1230 """ return sum([x * y for x, y in zip(X, Y)])
def dotproduct(X, Y): """Return the sum of the element-wise product of vectors x and y. >>> dotproduct([1, 2, 3], [1000, 100, 10]) 1230 """ return sum([x * y for x, y in zip(X, Y)])
[ "Return", "the", "sum", "of", "the", "element", "-", "wise", "product", "of", "vectors", "x", "and", "y", ".", ">>>", "dotproduct", "(", "[", "1", "2", "3", "]", "[", "1000", "100", "10", "]", ")", "1230" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L489-L494
[ "def", "dotproduct", "(", "X", ",", "Y", ")", ":", "return", "sum", "(", "[", "x", "*", "y", "for", "x", ",", "y", "in", "zip", "(", "X", ",", "Y", ")", "]", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
weighted_sample_with_replacement
Pick n samples from seq at random, with replacement, with the probability of each element in proportion to its corresponding weight.
aima/utils.py
def weighted_sample_with_replacement(seq, weights, n): """Pick n samples from seq at random, with replacement, with the probability of each element in proportion to its corresponding weight.""" sample = weighted_sampler(seq, weights) return [sample() for s in range(n)]
def weighted_sample_with_replacement(seq, weights, n): """Pick n samples from seq at random, with replacement, with the probability of each element in proportion to its corresponding weight.""" sample = weighted_sampler(seq, weights) return [sample() for s in range(n)]
[ "Pick", "n", "samples", "from", "seq", "at", "random", "with", "replacement", "with", "the", "probability", "of", "each", "element", "in", "proportion", "to", "its", "corresponding", "weight", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L507-L512
[ "def", "weighted_sample_with_replacement", "(", "seq", ",", "weights", ",", "n", ")", ":", "sample", "=", "weighted_sampler", "(", "seq", ",", "weights", ")", "return", "[", "sample", "(", ")", "for", "s", "in", "range", "(", "n", ")", "]" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
weighted_sampler
Return a random-sample function that picks from seq weighted by weights.
aima/utils.py
def weighted_sampler(seq, weights): "Return a random-sample function that picks from seq weighted by weights." totals = [] for w in weights: totals.append(w + totals[-1] if totals else w) return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]
def weighted_sampler(seq, weights): "Return a random-sample function that picks from seq weighted by weights." totals = [] for w in weights: totals.append(w + totals[-1] if totals else w) return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]
[ "Return", "a", "random", "-", "sample", "function", "that", "picks", "from", "seq", "weighted", "by", "weights", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L514-L519
[ "def", "weighted_sampler", "(", "seq", ",", "weights", ")", ":", "totals", "=", "[", "]", "for", "w", "in", "weights", ":", "totals", ".", "append", "(", "w", "+", "totals", "[", "-", "1", "]", "if", "totals", "else", "w", ")", "return", "lambda", ":", "seq", "[", "bisect", ".", "bisect", "(", "totals", ",", "random", ".", "uniform", "(", "0", ",", "totals", "[", "-", "1", "]", ")", ")", "]" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
num_or_str
The argument is a string; convert to a number if possible, or strip it. >>> num_or_str('42') 42 >>> num_or_str(' 42x ') '42x'
aima/utils.py
def num_or_str(x): """The argument is a string; convert to a number if possible, or strip it. >>> num_or_str('42') 42 >>> num_or_str(' 42x ') '42x' """ if isnumber(x): return x try: return int(x) except ValueError: try: return float(x) except ValueError: return str(x).strip()
def num_or_str(x): """The argument is a string; convert to a number if possible, or strip it. >>> num_or_str('42') 42 >>> num_or_str(' 42x ') '42x' """ if isnumber(x): return x try: return int(x) except ValueError: try: return float(x) except ValueError: return str(x).strip()
[ "The", "argument", "is", "a", "string", ";", "convert", "to", "a", "number", "if", "possible", "or", "strip", "it", ".", ">>>", "num_or_str", "(", "42", ")", "42", ">>>", "num_or_str", "(", "42x", ")", "42x" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L521-L535
[ "def", "num_or_str", "(", "x", ")", ":", "if", "isnumber", "(", "x", ")", ":", "return", "x", "try", ":", "return", "int", "(", "x", ")", "except", "ValueError", ":", "try", ":", "return", "float", "(", "x", ")", "except", "ValueError", ":", "return", "str", "(", "x", ")", ".", "strip", "(", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
normalize
Multiply each number by a constant such that the sum is 1.0 >>> normalize([1,2,1]) [0.25, 0.5, 0.25]
aima/utils.py
def normalize(numbers): """Multiply each number by a constant such that the sum is 1.0 >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ total = float(sum(numbers)) return [n / total for n in numbers]
def normalize(numbers): """Multiply each number by a constant such that the sum is 1.0 >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ total = float(sum(numbers)) return [n / total for n in numbers]
[ "Multiply", "each", "number", "by", "a", "constant", "such", "that", "the", "sum", "is", "1", ".", "0", ">>>", "normalize", "(", "[", "1", "2", "1", "]", ")", "[", "0", ".", "25", "0", ".", "5", "0", ".", "25", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L537-L543
[ "def", "normalize", "(", "numbers", ")", ":", "total", "=", "float", "(", "sum", "(", "numbers", ")", ")", "return", "[", "n", "/", "total", "for", "n", "in", "numbers", "]" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
distance
The distance between two (x, y) points.
aima/utils.py
def distance((ax, ay), (bx, by)): "The distance between two (x, y) points." return math.hypot((ax - bx), (ay - by))
def distance((ax, ay), (bx, by)): "The distance between two (x, y) points." return math.hypot((ax - bx), (ay - by))
[ "The", "distance", "between", "two", "(", "x", "y", ")", "points", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L568-L570
[ "def", "distance", "(", "(", "ax", ",", "ay", ")", ",", "(", "bx", ",", "by", ")", ")", ":", "return", "math", ".", "hypot", "(", "(", "ax", "-", "bx", ")", ",", "(", "ay", "-", "by", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
vector_clip
Return vector, except if any element is less than the corresponding value of lowest or more than the corresponding value of highest, clip to those values. >>> vector_clip((-1, 10), (0, 0), (9, 9)) (0, 9)
aima/utils.py
def vector_clip(vector, lowest, highest): """Return vector, except if any element is less than the corresponding value of lowest or more than the corresponding value of highest, clip to those values. >>> vector_clip((-1, 10), (0, 0), (9, 9)) (0, 9) """ return type(vector)(map(clip, vector, lowest, highest))
def vector_clip(vector, lowest, highest): """Return vector, except if any element is less than the corresponding value of lowest or more than the corresponding value of highest, clip to those values. >>> vector_clip((-1, 10), (0, 0), (9, 9)) (0, 9) """ return type(vector)(map(clip, vector, lowest, highest))
[ "Return", "vector", "except", "if", "any", "element", "is", "less", "than", "the", "corresponding", "value", "of", "lowest", "or", "more", "than", "the", "corresponding", "value", "of", "highest", "clip", "to", "those", "values", ".", ">>>", "vector_clip", "((", "-", "1", "10", ")", "(", "0", "0", ")", "(", "9", "9", "))", "(", "0", "9", ")" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L576-L583
[ "def", "vector_clip", "(", "vector", ",", "lowest", ",", "highest", ")", ":", "return", "type", "(", "vector", ")", "(", "map", "(", "clip", ",", "vector", ",", "lowest", ",", "highest", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
printf
Format args with the first argument as format string, and write. Return the last arg, or format itself if there are no args.
aima/utils.py
def printf(format, *args): """Format args with the first argument as format string, and write. Return the last arg, or format itself if there are no args.""" sys.stdout.write(str(format) % args) return if_(args, lambda: args[-1], lambda: format)
def printf(format, *args): """Format args with the first argument as format string, and write. Return the last arg, or format itself if there are no args.""" sys.stdout.write(str(format) % args) return if_(args, lambda: args[-1], lambda: format)
[ "Format", "args", "with", "the", "first", "argument", "as", "format", "string", "and", "write", ".", "Return", "the", "last", "arg", "or", "format", "itself", "if", "there", "are", "no", "args", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L588-L592
[ "def", "printf", "(", "format", ",", "*", "args", ")", ":", "sys", ".", "stdout", ".", "write", "(", "str", "(", "format", ")", "%", "args", ")", "return", "if_", "(", "args", ",", "lambda", ":", "args", "[", "-", "1", "]", ",", "lambda", ":", "format", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
memoize
Memoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, store results in a dictionary.
aima/utils.py
def memoize(fn, slot=None): """Memoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, store results in a dictionary.""" if slot: def memoized_fn(obj, *args): if hasattr(obj, slot): return getattr(obj, slot) else: val = fn(obj, *args) setattr(obj, slot, val) return val else: def memoized_fn(*args): if not memoized_fn.cache.has_key(args): memoized_fn.cache[args] = fn(*args) return memoized_fn.cache[args] memoized_fn.cache = {} return memoized_fn
def memoize(fn, slot=None): """Memoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, store results in a dictionary.""" if slot: def memoized_fn(obj, *args): if hasattr(obj, slot): return getattr(obj, slot) else: val = fn(obj, *args) setattr(obj, slot, val) return val else: def memoized_fn(*args): if not memoized_fn.cache.has_key(args): memoized_fn.cache[args] = fn(*args) return memoized_fn.cache[args] memoized_fn.cache = {} return memoized_fn
[ "Memoize", "fn", ":", "make", "it", "remember", "the", "computed", "value", "for", "any", "argument", "list", ".", "If", "slot", "is", "specified", "store", "result", "in", "that", "slot", "of", "first", "argument", ".", "If", "slot", "is", "false", "store", "results", "in", "a", "dictionary", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L606-L624
[ "def", "memoize", "(", "fn", ",", "slot", "=", "None", ")", ":", "if", "slot", ":", "def", "memoized_fn", "(", "obj", ",", "*", "args", ")", ":", "if", "hasattr", "(", "obj", ",", "slot", ")", ":", "return", "getattr", "(", "obj", ",", "slot", ")", "else", ":", "val", "=", "fn", "(", "obj", ",", "*", "args", ")", "setattr", "(", "obj", ",", "slot", ",", "val", ")", "return", "val", "else", ":", "def", "memoized_fn", "(", "*", "args", ")", ":", "if", "not", "memoized_fn", ".", "cache", ".", "has_key", "(", "args", ")", ":", "memoized_fn", ".", "cache", "[", "args", "]", "=", "fn", "(", "*", "args", ")", "return", "memoized_fn", ".", "cache", "[", "args", "]", "memoized_fn", ".", "cache", "=", "{", "}", "return", "memoized_fn" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
if_
Like C++ and Java's (test ? result : alternative), except both result and alternative are always evaluated. However, if either evaluates to a function, it is applied to the empty arglist, so you can delay execution by putting it in a lambda. >>> if_(2 + 2 == 4, 'ok', lambda: expensive_computation()) 'ok'
aima/utils.py
def if_(test, result, alternative): """Like C++ and Java's (test ? result : alternative), except both result and alternative are always evaluated. However, if either evaluates to a function, it is applied to the empty arglist, so you can delay execution by putting it in a lambda. >>> if_(2 + 2 == 4, 'ok', lambda: expensive_computation()) 'ok' """ if test: if callable(result): return result() return result else: if callable(alternative): return alternative() return alternative
def if_(test, result, alternative): """Like C++ and Java's (test ? result : alternative), except both result and alternative are always evaluated. However, if either evaluates to a function, it is applied to the empty arglist, so you can delay execution by putting it in a lambda. >>> if_(2 + 2 == 4, 'ok', lambda: expensive_computation()) 'ok' """ if test: if callable(result): return result() return result else: if callable(alternative): return alternative() return alternative
[ "Like", "C", "++", "and", "Java", "s", "(", "test", "?", "result", ":", "alternative", ")", "except", "both", "result", "and", "alternative", "are", "always", "evaluated", ".", "However", "if", "either", "evaluates", "to", "a", "function", "it", "is", "applied", "to", "the", "empty", "arglist", "so", "you", "can", "delay", "execution", "by", "putting", "it", "in", "a", "lambda", ".", ">>>", "if_", "(", "2", "+", "2", "==", "4", "ok", "lambda", ":", "expensive_computation", "()", ")", "ok" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L626-L639
[ "def", "if_", "(", "test", ",", "result", ",", "alternative", ")", ":", "if", "test", ":", "if", "callable", "(", "result", ")", ":", "return", "result", "(", ")", "return", "result", "else", ":", "if", "callable", "(", "alternative", ")", ":", "return", "alternative", "(", ")", "return", "alternative" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
name
Try to find some reasonable name for the object.
aima/utils.py
def name(object): "Try to find some reasonable name for the object." return (getattr(object, 'name', 0) or getattr(object, '__name__', 0) or getattr(getattr(object, '__class__', 0), '__name__', 0) or str(object))
def name(object): "Try to find some reasonable name for the object." return (getattr(object, 'name', 0) or getattr(object, '__name__', 0) or getattr(getattr(object, '__class__', 0), '__name__', 0) or str(object))
[ "Try", "to", "find", "some", "reasonable", "name", "for", "the", "object", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L641-L645
[ "def", "name", "(", "object", ")", ":", "return", "(", "getattr", "(", "object", ",", "'name'", ",", "0", ")", "or", "getattr", "(", "object", ",", "'__name__'", ",", "0", ")", "or", "getattr", "(", "getattr", "(", "object", ",", "'__class__'", ",", "0", ")", ",", "'__name__'", ",", "0", ")", "or", "str", "(", "object", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
print_table
Print a list of lists as a table, so that columns line up nicely. header, if specified, will be printed as the first row. numfmt is the format for all numbers; you might want e.g. '%6.2f'. (If you want different formats in different columns, don't use print_table.) sep is the separator between columns.
aima/utils.py
def print_table(table, header=None, sep=' ', numfmt='%g'): """Print a list of lists as a table, so that columns line up nicely. header, if specified, will be printed as the first row. numfmt is the format for all numbers; you might want e.g. '%6.2f'. (If you want different formats in different columns, don't use print_table.) sep is the separator between columns.""" justs = [if_(isnumber(x), 'rjust', 'ljust') for x in table[0]] if header: table = [header] + table table = [[if_(isnumber(x), lambda: numfmt % x, lambda: x) for x in row] for row in table] maxlen = lambda seq: max(map(len, seq)) sizes = map(maxlen, zip(*[map(str, row) for row in table])) for row in table: print sep.join(getattr(str(x), j)(size) for (j, size, x) in zip(justs, sizes, row))
def print_table(table, header=None, sep=' ', numfmt='%g'): """Print a list of lists as a table, so that columns line up nicely. header, if specified, will be printed as the first row. numfmt is the format for all numbers; you might want e.g. '%6.2f'. (If you want different formats in different columns, don't use print_table.) sep is the separator between columns.""" justs = [if_(isnumber(x), 'rjust', 'ljust') for x in table[0]] if header: table = [header] + table table = [[if_(isnumber(x), lambda: numfmt % x, lambda: x) for x in row] for row in table] maxlen = lambda seq: max(map(len, seq)) sizes = map(maxlen, zip(*[map(str, row) for row in table])) for row in table: print sep.join(getattr(str(x), j)(size) for (j, size, x) in zip(justs, sizes, row))
[ "Print", "a", "list", "of", "lists", "as", "a", "table", "so", "that", "columns", "line", "up", "nicely", ".", "header", "if", "specified", "will", "be", "printed", "as", "the", "first", "row", ".", "numfmt", "is", "the", "format", "for", "all", "numbers", ";", "you", "might", "want", "e", ".", "g", ".", "%6", ".", "2f", ".", "(", "If", "you", "want", "different", "formats", "in", "different", "columns", "don", "t", "use", "print_table", ".", ")", "sep", "is", "the", "separator", "between", "columns", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L655-L670
[ "def", "print_table", "(", "table", ",", "header", "=", "None", ",", "sep", "=", "' '", ",", "numfmt", "=", "'%g'", ")", ":", "justs", "=", "[", "if_", "(", "isnumber", "(", "x", ")", ",", "'rjust'", ",", "'ljust'", ")", "for", "x", "in", "table", "[", "0", "]", "]", "if", "header", ":", "table", "=", "[", "header", "]", "+", "table", "table", "=", "[", "[", "if_", "(", "isnumber", "(", "x", ")", ",", "lambda", ":", "numfmt", "%", "x", ",", "lambda", ":", "x", ")", "for", "x", "in", "row", "]", "for", "row", "in", "table", "]", "maxlen", "=", "lambda", "seq", ":", "max", "(", "map", "(", "len", ",", "seq", ")", ")", "sizes", "=", "map", "(", "maxlen", ",", "zip", "(", "*", "[", "map", "(", "str", ",", "row", ")", "for", "row", "in", "table", "]", ")", ")", "for", "row", "in", "table", ":", "print", "sep", ".", "join", "(", "getattr", "(", "str", "(", "x", ")", ",", "j", ")", "(", "size", ")", "for", "(", "j", ",", "size", ",", "x", ")", "in", "zip", "(", "justs", ",", "sizes", ",", "row", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
AIMAFile
Open a file based at the AIMA root directory.
aima/utils.py
def AIMAFile(components, mode='r'): "Open a file based at the AIMA root directory." import utils dir = os.path.dirname(utils.__file__) return open(apply(os.path.join, [dir] + components), mode)
def AIMAFile(components, mode='r'): "Open a file based at the AIMA root directory." import utils dir = os.path.dirname(utils.__file__) return open(apply(os.path.join, [dir] + components), mode)
[ "Open", "a", "file", "based", "at", "the", "AIMA", "root", "directory", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L672-L676
[ "def", "AIMAFile", "(", "components", ",", "mode", "=", "'r'", ")", ":", "import", "utils", "dir", "=", "os", ".", "path", ".", "dirname", "(", "utils", ".", "__file__", ")", "return", "open", "(", "apply", "(", "os", ".", "path", ".", "join", ",", "[", "dir", "]", "+", "components", ")", ",", "mode", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
parse_csv
r"""Input is a string consisting of lines, each line has comma-delimited fields. Convert this into a list of lists. Blank lines are skipped. Fields that look like numbers are converted to numbers. The delim defaults to ',' but '\t' and None are also reasonable values. >>> parse_csv('1, 2, 3 \n 0, 2, na') [[1, 2, 3], [0, 2, 'na']]
aima/learning.py
def parse_csv(input, delim=','): r"""Input is a string consisting of lines, each line has comma-delimited fields. Convert this into a list of lists. Blank lines are skipped. Fields that look like numbers are converted to numbers. The delim defaults to ',' but '\t' and None are also reasonable values. >>> parse_csv('1, 2, 3 \n 0, 2, na') [[1, 2, 3], [0, 2, 'na']] """ lines = [line for line in input.splitlines() if line.strip()] return [map(num_or_str, line.split(delim)) for line in lines]
def parse_csv(input, delim=','): r"""Input is a string consisting of lines, each line has comma-delimited fields. Convert this into a list of lists. Blank lines are skipped. Fields that look like numbers are converted to numbers. The delim defaults to ',' but '\t' and None are also reasonable values. >>> parse_csv('1, 2, 3 \n 0, 2, na') [[1, 2, 3], [0, 2, 'na']] """ lines = [line for line in input.splitlines() if line.strip()] return [map(num_or_str, line.split(delim)) for line in lines]
[ "r", "Input", "is", "a", "string", "consisting", "of", "lines", "each", "line", "has", "comma", "-", "delimited", "fields", ".", "Convert", "this", "into", "a", "list", "of", "lists", ".", "Blank", "lines", "are", "skipped", ".", "Fields", "that", "look", "like", "numbers", "are", "converted", "to", "numbers", ".", "The", "delim", "defaults", "to", "but", "\\", "t", "and", "None", "are", "also", "reasonable", "values", ".", ">>>", "parse_csv", "(", "1", "2", "3", "\\", "n", "0", "2", "na", ")", "[[", "1", "2", "3", "]", "[", "0", "2", "na", "]]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L132-L141
[ "def", "parse_csv", "(", "input", ",", "delim", "=", "','", ")", ":", "lines", "=", "[", "line", "for", "line", "in", "input", ".", "splitlines", "(", ")", "if", "line", ".", "strip", "(", ")", "]", "return", "[", "map", "(", "num_or_str", ",", "line", ".", "split", "(", "delim", ")", ")", "for", "line", "in", "lines", "]" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
PluralityLearner
A very dumb algorithm: always pick the result that was most popular in the training data. Makes a baseline for comparison.
aima/learning.py
def PluralityLearner(dataset): """A very dumb algorithm: always pick the result that was most popular in the training data. Makes a baseline for comparison.""" most_popular = mode([e[dataset.target] for e in dataset.examples]) def predict(example): "Always return same result: the most popular from the training set." return most_popular return predict
def PluralityLearner(dataset): """A very dumb algorithm: always pick the result that was most popular in the training data. Makes a baseline for comparison.""" most_popular = mode([e[dataset.target] for e in dataset.examples]) def predict(example): "Always return same result: the most popular from the training set." return most_popular return predict
[ "A", "very", "dumb", "algorithm", ":", "always", "pick", "the", "result", "that", "was", "most", "popular", "in", "the", "training", "data", ".", "Makes", "a", "baseline", "for", "comparison", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L196-L203
[ "def", "PluralityLearner", "(", "dataset", ")", ":", "most_popular", "=", "mode", "(", "[", "e", "[", "dataset", ".", "target", "]", "for", "e", "in", "dataset", ".", "examples", "]", ")", "def", "predict", "(", "example", ")", ":", "\"Always return same result: the most popular from the training set.\"", "return", "most_popular", "return", "predict" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
NaiveBayesLearner
Just count how many times each value of each input attribute occurs, conditional on the target value. Count the different target values too.
aima/learning.py
def NaiveBayesLearner(dataset): """Just count how many times each value of each input attribute occurs, conditional on the target value. Count the different target values too.""" targetvals = dataset.values[dataset.target] target_dist = CountingProbDist(targetvals) attr_dists = dict(((gv, attr), CountingProbDist(dataset.values[attr])) for gv in targetvals for attr in dataset.inputs) for example in dataset.examples: targetval = example[dataset.target] target_dist.add(targetval) for attr in dataset.inputs: attr_dists[targetval, attr].add(example[attr]) def predict(example): """Predict the target value for example. Consider each possible value, and pick the most likely by looking at each attribute independently.""" def class_probability(targetval): return (target_dist[targetval] * product(attr_dists[targetval, attr][example[attr]] for attr in dataset.inputs)) return argmax(targetvals, class_probability) return predict
def NaiveBayesLearner(dataset): """Just count how many times each value of each input attribute occurs, conditional on the target value. Count the different target values too.""" targetvals = dataset.values[dataset.target] target_dist = CountingProbDist(targetvals) attr_dists = dict(((gv, attr), CountingProbDist(dataset.values[attr])) for gv in targetvals for attr in dataset.inputs) for example in dataset.examples: targetval = example[dataset.target] target_dist.add(targetval) for attr in dataset.inputs: attr_dists[targetval, attr].add(example[attr]) def predict(example): """Predict the target value for example. Consider each possible value, and pick the most likely by looking at each attribute independently.""" def class_probability(targetval): return (target_dist[targetval] * product(attr_dists[targetval, attr][example[attr]] for attr in dataset.inputs)) return argmax(targetvals, class_probability) return predict
[ "Just", "count", "how", "many", "times", "each", "value", "of", "each", "input", "attribute", "occurs", "conditional", "on", "the", "target", "value", ".", "Count", "the", "different", "target", "values", "too", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L207-L232
[ "def", "NaiveBayesLearner", "(", "dataset", ")", ":", "targetvals", "=", "dataset", ".", "values", "[", "dataset", ".", "target", "]", "target_dist", "=", "CountingProbDist", "(", "targetvals", ")", "attr_dists", "=", "dict", "(", "(", "(", "gv", ",", "attr", ")", ",", "CountingProbDist", "(", "dataset", ".", "values", "[", "attr", "]", ")", ")", "for", "gv", "in", "targetvals", "for", "attr", "in", "dataset", ".", "inputs", ")", "for", "example", "in", "dataset", ".", "examples", ":", "targetval", "=", "example", "[", "dataset", ".", "target", "]", "target_dist", ".", "add", "(", "targetval", ")", "for", "attr", "in", "dataset", ".", "inputs", ":", "attr_dists", "[", "targetval", ",", "attr", "]", ".", "add", "(", "example", "[", "attr", "]", ")", "def", "predict", "(", "example", ")", ":", "\"\"\"Predict the target value for example. Consider each possible value,\n and pick the most likely by looking at each attribute independently.\"\"\"", "def", "class_probability", "(", "targetval", ")", ":", "return", "(", "target_dist", "[", "targetval", "]", "*", "product", "(", "attr_dists", "[", "targetval", ",", "attr", "]", "[", "example", "[", "attr", "]", "]", "for", "attr", "in", "dataset", ".", "inputs", ")", ")", "return", "argmax", "(", "targetvals", ",", "class_probability", ")", "return", "predict" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
NearestNeighborLearner
k-NearestNeighbor: the k nearest neighbors vote.
aima/learning.py
def NearestNeighborLearner(dataset, k=1): "k-NearestNeighbor: the k nearest neighbors vote." def predict(example): "Find the k closest, and have them vote for the best." best = heapq.nsmallest(k, ((dataset.distance(e, example), e) for e in dataset.examples)) return mode(e[dataset.target] for (d, e) in best) return predict
def NearestNeighborLearner(dataset, k=1): "k-NearestNeighbor: the k nearest neighbors vote." def predict(example): "Find the k closest, and have them vote for the best." best = heapq.nsmallest(k, ((dataset.distance(e, example), e) for e in dataset.examples)) return mode(e[dataset.target] for (d, e) in best) return predict
[ "k", "-", "NearestNeighbor", ":", "the", "k", "nearest", "neighbors", "vote", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L236-L243
[ "def", "NearestNeighborLearner", "(", "dataset", ",", "k", "=", "1", ")", ":", "def", "predict", "(", "example", ")", ":", "\"Find the k closest, and have them vote for the best.\"", "best", "=", "heapq", ".", "nsmallest", "(", "k", ",", "(", "(", "dataset", ".", "distance", "(", "e", ",", "example", ")", ",", "e", ")", "for", "e", "in", "dataset", ".", "examples", ")", ")", "return", "mode", "(", "e", "[", "dataset", ".", "target", "]", "for", "(", "d", ",", "e", ")", "in", "best", ")", "return", "predict" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
DecisionTreeLearner
[Fig. 18.5]
aima/learning.py
def DecisionTreeLearner(dataset): "[Fig. 18.5]" target, values = dataset.target, dataset.values def decision_tree_learning(examples, attrs, parent_examples=()): if len(examples) == 0: return plurality_value(parent_examples) elif all_same_class(examples): return DecisionLeaf(examples[0][target]) elif len(attrs) == 0: return plurality_value(examples) else: A = choose_attribute(attrs, examples) tree = DecisionFork(A, dataset.attrnames[A]) for (v_k, exs) in split_by(A, examples): subtree = decision_tree_learning( exs, removeall(A, attrs), examples) tree.add(v_k, subtree) return tree def plurality_value(examples): """Return the most popular target value for this set of examples. (If target is binary, this is the majority; otherwise plurality.)""" popular = argmax_random_tie(values[target], lambda v: count(target, v, examples)) return DecisionLeaf(popular) def count(attr, val, examples): return count_if(lambda e: e[attr] == val, examples) def all_same_class(examples): "Are all these examples in the same target class?" class0 = examples[0][target] return all(e[target] == class0 for e in examples) def choose_attribute(attrs, examples): "Choose the attribute with the highest information gain." return argmax_random_tie(attrs, lambda a: information_gain(a, examples)) def information_gain(attr, examples): "Return the expected reduction in entropy from splitting by attr." def I(examples): return information_content([count(target, v, examples) for v in values[target]]) N = float(len(examples)) remainder = sum((len(examples_i) / N) * I(examples_i) for (v, examples_i) in split_by(attr, examples)) return I(examples) - remainder def split_by(attr, examples): "Return a list of (val, examples) pairs for each val of attr." return [(v, [e for e in examples if e[attr] == v]) for v in values[attr]] return decision_tree_learning(dataset.examples, dataset.inputs)
def DecisionTreeLearner(dataset): "[Fig. 18.5]" target, values = dataset.target, dataset.values def decision_tree_learning(examples, attrs, parent_examples=()): if len(examples) == 0: return plurality_value(parent_examples) elif all_same_class(examples): return DecisionLeaf(examples[0][target]) elif len(attrs) == 0: return plurality_value(examples) else: A = choose_attribute(attrs, examples) tree = DecisionFork(A, dataset.attrnames[A]) for (v_k, exs) in split_by(A, examples): subtree = decision_tree_learning( exs, removeall(A, attrs), examples) tree.add(v_k, subtree) return tree def plurality_value(examples): """Return the most popular target value for this set of examples. (If target is binary, this is the majority; otherwise plurality.)""" popular = argmax_random_tie(values[target], lambda v: count(target, v, examples)) return DecisionLeaf(popular) def count(attr, val, examples): return count_if(lambda e: e[attr] == val, examples) def all_same_class(examples): "Are all these examples in the same target class?" class0 = examples[0][target] return all(e[target] == class0 for e in examples) def choose_attribute(attrs, examples): "Choose the attribute with the highest information gain." return argmax_random_tie(attrs, lambda a: information_gain(a, examples)) def information_gain(attr, examples): "Return the expected reduction in entropy from splitting by attr." def I(examples): return information_content([count(target, v, examples) for v in values[target]]) N = float(len(examples)) remainder = sum((len(examples_i) / N) * I(examples_i) for (v, examples_i) in split_by(attr, examples)) return I(examples) - remainder def split_by(attr, examples): "Return a list of (val, examples) pairs for each val of attr." return [(v, [e for e in examples if e[attr] == v]) for v in values[attr]] return decision_tree_learning(dataset.examples, dataset.inputs)
[ "[", "Fig", ".", "18", ".", "5", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L293-L349
[ "def", "DecisionTreeLearner", "(", "dataset", ")", ":", "target", ",", "values", "=", "dataset", ".", "target", ",", "dataset", ".", "values", "def", "decision_tree_learning", "(", "examples", ",", "attrs", ",", "parent_examples", "=", "(", ")", ")", ":", "if", "len", "(", "examples", ")", "==", "0", ":", "return", "plurality_value", "(", "parent_examples", ")", "elif", "all_same_class", "(", "examples", ")", ":", "return", "DecisionLeaf", "(", "examples", "[", "0", "]", "[", "target", "]", ")", "elif", "len", "(", "attrs", ")", "==", "0", ":", "return", "plurality_value", "(", "examples", ")", "else", ":", "A", "=", "choose_attribute", "(", "attrs", ",", "examples", ")", "tree", "=", "DecisionFork", "(", "A", ",", "dataset", ".", "attrnames", "[", "A", "]", ")", "for", "(", "v_k", ",", "exs", ")", "in", "split_by", "(", "A", ",", "examples", ")", ":", "subtree", "=", "decision_tree_learning", "(", "exs", ",", "removeall", "(", "A", ",", "attrs", ")", ",", "examples", ")", "tree", ".", "add", "(", "v_k", ",", "subtree", ")", "return", "tree", "def", "plurality_value", "(", "examples", ")", ":", "\"\"\"Return the most popular target value for this set of examples.\n (If target is binary, this is the majority; otherwise plurality.)\"\"\"", "popular", "=", "argmax_random_tie", "(", "values", "[", "target", "]", ",", "lambda", "v", ":", "count", "(", "target", ",", "v", ",", "examples", ")", ")", "return", "DecisionLeaf", "(", "popular", ")", "def", "count", "(", "attr", ",", "val", ",", "examples", ")", ":", "return", "count_if", "(", "lambda", "e", ":", "e", "[", "attr", "]", "==", "val", ",", "examples", ")", "def", "all_same_class", "(", "examples", ")", ":", "\"Are all these examples in the same target class?\"", "class0", "=", "examples", "[", "0", "]", "[", "target", "]", "return", "all", "(", "e", "[", "target", "]", "==", "class0", "for", "e", "in", "examples", ")", "def", "choose_attribute", "(", "attrs", ",", "examples", ")", ":", "\"Choose the attribute with the highest information gain.\"", "return", "argmax_random_tie", "(", "attrs", ",", "lambda", "a", ":", "information_gain", "(", "a", ",", "examples", ")", ")", "def", "information_gain", "(", "attr", ",", "examples", ")", ":", "\"Return the expected reduction in entropy from splitting by attr.\"", "def", "I", "(", "examples", ")", ":", "return", "information_content", "(", "[", "count", "(", "target", ",", "v", ",", "examples", ")", "for", "v", "in", "values", "[", "target", "]", "]", ")", "N", "=", "float", "(", "len", "(", "examples", ")", ")", "remainder", "=", "sum", "(", "(", "len", "(", "examples_i", ")", "/", "N", ")", "*", "I", "(", "examples_i", ")", "for", "(", "v", ",", "examples_i", ")", "in", "split_by", "(", "attr", ",", "examples", ")", ")", "return", "I", "(", "examples", ")", "-", "remainder", "def", "split_by", "(", "attr", ",", "examples", ")", ":", "\"Return a list of (val, examples) pairs for each val of attr.\"", "return", "[", "(", "v", ",", "[", "e", "for", "e", "in", "examples", "if", "e", "[", "attr", "]", "==", "v", "]", ")", "for", "v", "in", "values", "[", "attr", "]", "]", "return", "decision_tree_learning", "(", "dataset", ".", "examples", ",", "dataset", ".", "inputs", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
information_content
Number of bits to represent the probability distribution in values.
aima/learning.py
def information_content(values): "Number of bits to represent the probability distribution in values." probabilities = normalize(removeall(0, values)) return sum(-p * log2(p) for p in probabilities)
def information_content(values): "Number of bits to represent the probability distribution in values." probabilities = normalize(removeall(0, values)) return sum(-p * log2(p) for p in probabilities)
[ "Number", "of", "bits", "to", "represent", "the", "probability", "distribution", "in", "values", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L351-L354
[ "def", "information_content", "(", "values", ")", ":", "probabilities", "=", "normalize", "(", "removeall", "(", "0", ",", "values", ")", ")", "return", "sum", "(", "-", "p", "*", "log2", "(", "p", ")", "for", "p", "in", "probabilities", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
DecisionListLearner
[Fig. 18.11]
aima/learning.py
def DecisionListLearner(dataset): """[Fig. 18.11]""" def decision_list_learning(examples): if not examples: return [(True, False)] t, o, examples_t = find_examples(examples) if not t: raise Failure return [(t, o)] + decision_list_learning(examples - examples_t) def find_examples(examples): """Find a set of examples that all have the same outcome under some test. Return a tuple of the test, outcome, and examples.""" unimplemented() def passes(example, test): "Does the example pass the test?" unimplemented() def predict(example): "Predict the outcome for the first passing test." for test, outcome in predict.decision_list: if passes(example, test): return outcome predict.decision_list = decision_list_learning(set(dataset.examples)) return predict
def DecisionListLearner(dataset): """[Fig. 18.11]""" def decision_list_learning(examples): if not examples: return [(True, False)] t, o, examples_t = find_examples(examples) if not t: raise Failure return [(t, o)] + decision_list_learning(examples - examples_t) def find_examples(examples): """Find a set of examples that all have the same outcome under some test. Return a tuple of the test, outcome, and examples.""" unimplemented() def passes(example, test): "Does the example pass the test?" unimplemented() def predict(example): "Predict the outcome for the first passing test." for test, outcome in predict.decision_list: if passes(example, test): return outcome predict.decision_list = decision_list_learning(set(dataset.examples)) return predict
[ "[", "Fig", ".", "18", ".", "11", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L360-L387
[ "def", "DecisionListLearner", "(", "dataset", ")", ":", "def", "decision_list_learning", "(", "examples", ")", ":", "if", "not", "examples", ":", "return", "[", "(", "True", ",", "False", ")", "]", "t", ",", "o", ",", "examples_t", "=", "find_examples", "(", "examples", ")", "if", "not", "t", ":", "raise", "Failure", "return", "[", "(", "t", ",", "o", ")", "]", "+", "decision_list_learning", "(", "examples", "-", "examples_t", ")", "def", "find_examples", "(", "examples", ")", ":", "\"\"\"Find a set of examples that all have the same outcome under\n some test. Return a tuple of the test, outcome, and examples.\"\"\"", "unimplemented", "(", ")", "def", "passes", "(", "example", ",", "test", ")", ":", "\"Does the example pass the test?\"", "unimplemented", "(", ")", "def", "predict", "(", "example", ")", ":", "\"Predict the outcome for the first passing test.\"", "for", "test", ",", "outcome", "in", "predict", ".", "decision_list", ":", "if", "passes", "(", "example", ",", "test", ")", ":", "return", "outcome", "predict", ".", "decision_list", "=", "decision_list_learning", "(", "set", "(", "dataset", ".", "examples", ")", ")", "return", "predict" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
NeuralNetLearner
Layered feed-forward network.
aima/learning.py
def NeuralNetLearner(dataset, sizes): """Layered feed-forward network.""" activations = map(lambda n: [0.0 for i in range(n)], sizes) weights = [] def predict(example): unimplemented() return predict
def NeuralNetLearner(dataset, sizes): """Layered feed-forward network.""" activations = map(lambda n: [0.0 for i in range(n)], sizes) weights = [] def predict(example): unimplemented() return predict
[ "Layered", "feed", "-", "forward", "network", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L391-L400
[ "def", "NeuralNetLearner", "(", "dataset", ",", "sizes", ")", ":", "activations", "=", "map", "(", "lambda", "n", ":", "[", "0.0", "for", "i", "in", "range", "(", "n", ")", "]", ",", "sizes", ")", "weights", "=", "[", "]", "def", "predict", "(", "example", ")", ":", "unimplemented", "(", ")", "return", "predict" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
EnsembleLearner
Given a list of learning algorithms, have them vote.
aima/learning.py
def EnsembleLearner(learners): """Given a list of learning algorithms, have them vote.""" def train(dataset): predictors = [learner(dataset) for learner in learners] def predict(example): return mode(predictor(example) for predictor in predictors) return predict return train
def EnsembleLearner(learners): """Given a list of learning algorithms, have them vote.""" def train(dataset): predictors = [learner(dataset) for learner in learners] def predict(example): return mode(predictor(example) for predictor in predictors) return predict return train
[ "Given", "a", "list", "of", "learning", "algorithms", "have", "them", "vote", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L418-L425
[ "def", "EnsembleLearner", "(", "learners", ")", ":", "def", "train", "(", "dataset", ")", ":", "predictors", "=", "[", "learner", "(", "dataset", ")", "for", "learner", "in", "learners", "]", "def", "predict", "(", "example", ")", ":", "return", "mode", "(", "predictor", "(", "example", ")", "for", "predictor", "in", "predictors", ")", "return", "predict", "return", "train" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
AdaBoost
[Fig. 18.34]
aima/learning.py
def AdaBoost(L, K): """[Fig. 18.34]""" def train(dataset): examples, target = dataset.examples, dataset.target N = len(examples) epsilon = 1./(2*N) w = [1./N] * N h, z = [], [] for k in range(K): h_k = L(dataset, w) h.append(h_k) error = sum(weight for example, weight in zip(examples, w) if example[target] != h_k(example)) # Avoid divide-by-0 from either 0% or 100% error rates: error = clip(error, epsilon, 1-epsilon) for j, example in enumerate(examples): if example[target] == h_k(example): w[j] *= error / (1. - error) w = normalize(w) z.append(math.log((1. - error) / error)) return WeightedMajority(h, z) return train
def AdaBoost(L, K): """[Fig. 18.34]""" def train(dataset): examples, target = dataset.examples, dataset.target N = len(examples) epsilon = 1./(2*N) w = [1./N] * N h, z = [], [] for k in range(K): h_k = L(dataset, w) h.append(h_k) error = sum(weight for example, weight in zip(examples, w) if example[target] != h_k(example)) # Avoid divide-by-0 from either 0% or 100% error rates: error = clip(error, epsilon, 1-epsilon) for j, example in enumerate(examples): if example[target] == h_k(example): w[j] *= error / (1. - error) w = normalize(w) z.append(math.log((1. - error) / error)) return WeightedMajority(h, z) return train
[ "[", "Fig", ".", "18", ".", "34", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L429-L450
[ "def", "AdaBoost", "(", "L", ",", "K", ")", ":", "def", "train", "(", "dataset", ")", ":", "examples", ",", "target", "=", "dataset", ".", "examples", ",", "dataset", ".", "target", "N", "=", "len", "(", "examples", ")", "epsilon", "=", "1.", "/", "(", "2", "*", "N", ")", "w", "=", "[", "1.", "/", "N", "]", "*", "N", "h", ",", "z", "=", "[", "]", ",", "[", "]", "for", "k", "in", "range", "(", "K", ")", ":", "h_k", "=", "L", "(", "dataset", ",", "w", ")", "h", ".", "append", "(", "h_k", ")", "error", "=", "sum", "(", "weight", "for", "example", ",", "weight", "in", "zip", "(", "examples", ",", "w", ")", "if", "example", "[", "target", "]", "!=", "h_k", "(", "example", ")", ")", "# Avoid divide-by-0 from either 0% or 100% error rates:", "error", "=", "clip", "(", "error", ",", "epsilon", ",", "1", "-", "epsilon", ")", "for", "j", ",", "example", "in", "enumerate", "(", "examples", ")", ":", "if", "example", "[", "target", "]", "==", "h_k", "(", "example", ")", ":", "w", "[", "j", "]", "*=", "error", "/", "(", "1.", "-", "error", ")", "w", "=", "normalize", "(", "w", ")", "z", ".", "append", "(", "math", ".", "log", "(", "(", "1.", "-", "error", ")", "/", "error", ")", ")", "return", "WeightedMajority", "(", "h", ",", "z", ")", "return", "train" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
WeightedMajority
Return a predictor that takes a weighted vote.
aima/learning.py
def WeightedMajority(predictors, weights): "Return a predictor that takes a weighted vote." def predict(example): return weighted_mode((predictor(example) for predictor in predictors), weights) return predict
def WeightedMajority(predictors, weights): "Return a predictor that takes a weighted vote." def predict(example): return weighted_mode((predictor(example) for predictor in predictors), weights) return predict
[ "Return", "a", "predictor", "that", "takes", "a", "weighted", "vote", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L452-L457
[ "def", "WeightedMajority", "(", "predictors", ",", "weights", ")", ":", "def", "predict", "(", "example", ")", ":", "return", "weighted_mode", "(", "(", "predictor", "(", "example", ")", "for", "predictor", "in", "predictors", ")", ",", "weights", ")", "return", "predict" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
weighted_mode
Return the value with the greatest total weight. >>> weighted_mode('abbaa', [1,2,3,1,2]) 'b
aima/learning.py
def weighted_mode(values, weights): """Return the value with the greatest total weight. >>> weighted_mode('abbaa', [1,2,3,1,2]) 'b'""" totals = defaultdict(int) for v, w in zip(values, weights): totals[v] += w return max(totals.keys(), key=totals.get)
def weighted_mode(values, weights): """Return the value with the greatest total weight. >>> weighted_mode('abbaa', [1,2,3,1,2]) 'b'""" totals = defaultdict(int) for v, w in zip(values, weights): totals[v] += w return max(totals.keys(), key=totals.get)
[ "Return", "the", "value", "with", "the", "greatest", "total", "weight", ".", ">>>", "weighted_mode", "(", "abbaa", "[", "1", "2", "3", "1", "2", "]", ")", "b" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L459-L466
[ "def", "weighted_mode", "(", "values", ",", "weights", ")", ":", "totals", "=", "defaultdict", "(", "int", ")", "for", "v", ",", "w", "in", "zip", "(", "values", ",", "weights", ")", ":", "totals", "[", "v", "]", "+=", "w", "return", "max", "(", "totals", ".", "keys", "(", ")", ",", "key", "=", "totals", ".", "get", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
WeightedLearner
Given a learner that takes just an unweighted dataset, return one that takes also a weight for each example. [p. 749 footnote 14]
aima/learning.py
def WeightedLearner(unweighted_learner): """Given a learner that takes just an unweighted dataset, return one that takes also a weight for each example. [p. 749 footnote 14]""" def train(dataset, weights): return unweighted_learner(replicated_dataset(dataset, weights)) return train
def WeightedLearner(unweighted_learner): """Given a learner that takes just an unweighted dataset, return one that takes also a weight for each example. [p. 749 footnote 14]""" def train(dataset, weights): return unweighted_learner(replicated_dataset(dataset, weights)) return train
[ "Given", "a", "learner", "that", "takes", "just", "an", "unweighted", "dataset", "return", "one", "that", "takes", "also", "a", "weight", "for", "each", "example", ".", "[", "p", ".", "749", "footnote", "14", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L471-L476
[ "def", "WeightedLearner", "(", "unweighted_learner", ")", ":", "def", "train", "(", "dataset", ",", "weights", ")", ":", "return", "unweighted_learner", "(", "replicated_dataset", "(", "dataset", ",", "weights", ")", ")", "return", "train" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
replicated_dataset
Copy dataset, replicating each example in proportion to its weight.
aima/learning.py
def replicated_dataset(dataset, weights, n=None): "Copy dataset, replicating each example in proportion to its weight." n = n or len(dataset.examples) result = copy.copy(dataset) result.examples = weighted_replicate(dataset.examples, weights, n) return result
def replicated_dataset(dataset, weights, n=None): "Copy dataset, replicating each example in proportion to its weight." n = n or len(dataset.examples) result = copy.copy(dataset) result.examples = weighted_replicate(dataset.examples, weights, n) return result
[ "Copy", "dataset", "replicating", "each", "example", "in", "proportion", "to", "its", "weight", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L478-L483
[ "def", "replicated_dataset", "(", "dataset", ",", "weights", ",", "n", "=", "None", ")", ":", "n", "=", "n", "or", "len", "(", "dataset", ".", "examples", ")", "result", "=", "copy", ".", "copy", "(", "dataset", ")", "result", ".", "examples", "=", "weighted_replicate", "(", "dataset", ".", "examples", ",", "weights", ",", "n", ")", "return", "result" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
weighted_replicate
Return n selections from seq, with the count of each element of seq proportional to the corresponding weight (filling in fractions randomly). >>> weighted_replicate('ABC', [1,2,1], 4) ['A', 'B', 'B', 'C']
aima/learning.py
def weighted_replicate(seq, weights, n): """Return n selections from seq, with the count of each element of seq proportional to the corresponding weight (filling in fractions randomly). >>> weighted_replicate('ABC', [1,2,1], 4) ['A', 'B', 'B', 'C']""" assert len(seq) == len(weights) weights = normalize(weights) wholes = [int(w*n) for w in weights] fractions = [(w*n) % 1 for w in weights] return (flatten([x] * nx for x, nx in zip(seq, wholes)) + weighted_sample_with_replacement(seq, fractions, n - sum(wholes)))
def weighted_replicate(seq, weights, n): """Return n selections from seq, with the count of each element of seq proportional to the corresponding weight (filling in fractions randomly). >>> weighted_replicate('ABC', [1,2,1], 4) ['A', 'B', 'B', 'C']""" assert len(seq) == len(weights) weights = normalize(weights) wholes = [int(w*n) for w in weights] fractions = [(w*n) % 1 for w in weights] return (flatten([x] * nx for x, nx in zip(seq, wholes)) + weighted_sample_with_replacement(seq, fractions, n - sum(wholes)))
[ "Return", "n", "selections", "from", "seq", "with", "the", "count", "of", "each", "element", "of", "seq", "proportional", "to", "the", "corresponding", "weight", "(", "filling", "in", "fractions", "randomly", ")", ".", ">>>", "weighted_replicate", "(", "ABC", "[", "1", "2", "1", "]", "4", ")", "[", "A", "B", "B", "C", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L485-L496
[ "def", "weighted_replicate", "(", "seq", ",", "weights", ",", "n", ")", ":", "assert", "len", "(", "seq", ")", "==", "len", "(", "weights", ")", "weights", "=", "normalize", "(", "weights", ")", "wholes", "=", "[", "int", "(", "w", "*", "n", ")", "for", "w", "in", "weights", "]", "fractions", "=", "[", "(", "w", "*", "n", ")", "%", "1", "for", "w", "in", "weights", "]", "return", "(", "flatten", "(", "[", "x", "]", "*", "nx", "for", "x", ",", "nx", "in", "zip", "(", "seq", ",", "wholes", ")", ")", "+", "weighted_sample_with_replacement", "(", "seq", ",", "fractions", ",", "n", "-", "sum", "(", "wholes", ")", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
cross_validation
Do k-fold cross_validate and return their mean. That is, keep out 1/k of the examples for testing on each of k runs. Shuffle the examples first; If trials>1, average over several shuffles.
aima/learning.py
def cross_validation(learner, dataset, k=10, trials=1): """Do k-fold cross_validate and return their mean. That is, keep out 1/k of the examples for testing on each of k runs. Shuffle the examples first; If trials>1, average over several shuffles.""" if k is None: k = len(dataset.examples) if trials > 1: return mean([cross_validation(learner, dataset, k, trials=1) for t in range(trials)]) else: n = len(dataset.examples) random.shuffle(dataset.examples) return mean([train_and_test(learner, dataset, i*(n/k), (i+1)*(n/k)) for i in range(k)])
def cross_validation(learner, dataset, k=10, trials=1): """Do k-fold cross_validate and return their mean. That is, keep out 1/k of the examples for testing on each of k runs. Shuffle the examples first; If trials>1, average over several shuffles.""" if k is None: k = len(dataset.examples) if trials > 1: return mean([cross_validation(learner, dataset, k, trials=1) for t in range(trials)]) else: n = len(dataset.examples) random.shuffle(dataset.examples) return mean([train_and_test(learner, dataset, i*(n/k), (i+1)*(n/k)) for i in range(k)])
[ "Do", "k", "-", "fold", "cross_validate", "and", "return", "their", "mean", ".", "That", "is", "keep", "out", "1", "/", "k", "of", "the", "examples", "for", "testing", "on", "each", "of", "k", "runs", ".", "Shuffle", "the", "examples", "first", ";", "If", "trials", ">", "1", "average", "over", "several", "shuffles", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L530-L543
[ "def", "cross_validation", "(", "learner", ",", "dataset", ",", "k", "=", "10", ",", "trials", "=", "1", ")", ":", "if", "k", "is", "None", ":", "k", "=", "len", "(", "dataset", ".", "examples", ")", "if", "trials", ">", "1", ":", "return", "mean", "(", "[", "cross_validation", "(", "learner", ",", "dataset", ",", "k", ",", "trials", "=", "1", ")", "for", "t", "in", "range", "(", "trials", ")", "]", ")", "else", ":", "n", "=", "len", "(", "dataset", ".", "examples", ")", "random", ".", "shuffle", "(", "dataset", ".", "examples", ")", "return", "mean", "(", "[", "train_and_test", "(", "learner", ",", "dataset", ",", "i", "*", "(", "n", "/", "k", ")", ",", "(", "i", "+", "1", ")", "*", "(", "n", "/", "k", ")", ")", "for", "i", "in", "range", "(", "k", ")", "]", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
leave1out
Leave one out cross-validation over the dataset.
aima/learning.py
def leave1out(learner, dataset): "Leave one out cross-validation over the dataset." return cross_validation(learner, dataset, k=len(dataset.examples))
def leave1out(learner, dataset): "Leave one out cross-validation over the dataset." return cross_validation(learner, dataset, k=len(dataset.examples))
[ "Leave", "one", "out", "cross", "-", "validation", "over", "the", "dataset", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L545-L547
[ "def", "leave1out", "(", "learner", ",", "dataset", ")", ":", "return", "cross_validation", "(", "learner", ",", "dataset", ",", "k", "=", "len", "(", "dataset", ".", "examples", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
SyntheticRestaurant
Generate a DataSet with n examples.
aima/learning.py
def SyntheticRestaurant(n=20): "Generate a DataSet with n examples." def gen(): example = map(random.choice, restaurant.values) example[restaurant.target] = Fig[18,2](example) return example return RestaurantDataSet([gen() for i in range(n)])
def SyntheticRestaurant(n=20): "Generate a DataSet with n examples." def gen(): example = map(random.choice, restaurant.values) example[restaurant.target] = Fig[18,2](example) return example return RestaurantDataSet([gen() for i in range(n)])
[ "Generate", "a", "DataSet", "with", "n", "examples", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L627-L633
[ "def", "SyntheticRestaurant", "(", "n", "=", "20", ")", ":", "def", "gen", "(", ")", ":", "example", "=", "map", "(", "random", ".", "choice", ",", "restaurant", ".", "values", ")", "example", "[", "restaurant", ".", "target", "]", "=", "Fig", "[", "18", ",", "2", "]", "(", "example", ")", "return", "example", "return", "RestaurantDataSet", "(", "[", "gen", "(", ")", "for", "i", "in", "range", "(", "n", ")", "]", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
Majority
Return a DataSet with n k-bit examples of the majority problem: k random bits followed by a 1 if more than half the bits are 1, else 0.
aima/learning.py
def Majority(k, n): """Return a DataSet with n k-bit examples of the majority problem: k random bits followed by a 1 if more than half the bits are 1, else 0.""" examples = [] for i in range(n): bits = [random.choice([0, 1]) for i in range(k)] bits.append(int(sum(bits) > k/2)) examples.append(bits) return DataSet(name="majority", examples=examples)
def Majority(k, n): """Return a DataSet with n k-bit examples of the majority problem: k random bits followed by a 1 if more than half the bits are 1, else 0.""" examples = [] for i in range(n): bits = [random.choice([0, 1]) for i in range(k)] bits.append(int(sum(bits) > k/2)) examples.append(bits) return DataSet(name="majority", examples=examples)
[ "Return", "a", "DataSet", "with", "n", "k", "-", "bit", "examples", "of", "the", "majority", "problem", ":", "k", "random", "bits", "followed", "by", "a", "1", "if", "more", "than", "half", "the", "bits", "are", "1", "else", "0", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L638-L646
[ "def", "Majority", "(", "k", ",", "n", ")", ":", "examples", "=", "[", "]", "for", "i", "in", "range", "(", "n", ")", ":", "bits", "=", "[", "random", ".", "choice", "(", "[", "0", ",", "1", "]", ")", "for", "i", "in", "range", "(", "k", ")", "]", "bits", ".", "append", "(", "int", "(", "sum", "(", "bits", ")", ">", "k", "/", "2", ")", ")", "examples", ".", "append", "(", "bits", ")", "return", "DataSet", "(", "name", "=", "\"majority\"", ",", "examples", "=", "examples", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
ContinuousXor
2 inputs are chosen uniformly from (0.0 .. 2.0]; output is xor of ints.
aima/learning.py
def ContinuousXor(n): "2 inputs are chosen uniformly from (0.0 .. 2.0]; output is xor of ints." examples = [] for i in range(n): x, y = [random.uniform(0.0, 2.0) for i in '12'] examples.append([x, y, int(x) != int(y)]) return DataSet(name="continuous xor", examples=examples)
def ContinuousXor(n): "2 inputs are chosen uniformly from (0.0 .. 2.0]; output is xor of ints." examples = [] for i in range(n): x, y = [random.uniform(0.0, 2.0) for i in '12'] examples.append([x, y, int(x) != int(y)]) return DataSet(name="continuous xor", examples=examples)
[ "2", "inputs", "are", "chosen", "uniformly", "from", "(", "0", ".", "0", "..", "2", ".", "0", "]", ";", "output", "is", "xor", "of", "ints", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L662-L668
[ "def", "ContinuousXor", "(", "n", ")", ":", "examples", "=", "[", "]", "for", "i", "in", "range", "(", "n", ")", ":", "x", ",", "y", "=", "[", "random", ".", "uniform", "(", "0.0", ",", "2.0", ")", "for", "i", "in", "'12'", "]", "examples", ".", "append", "(", "[", "x", ",", "y", ",", "int", "(", "x", ")", "!=", "int", "(", "y", ")", "]", ")", "return", "DataSet", "(", "name", "=", "\"continuous xor\"", ",", "examples", "=", "examples", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
compare
Compare various learners on various datasets using cross-validation. Print results as a table.
aima/learning.py
def compare(algorithms=[PluralityLearner, NaiveBayesLearner, NearestNeighborLearner, DecisionTreeLearner], datasets=[iris, orings, zoo, restaurant, SyntheticRestaurant(20), Majority(7, 100), Parity(7, 100), Xor(100)], k=10, trials=1): """Compare various learners on various datasets using cross-validation. Print results as a table.""" print_table([[a.__name__.replace('Learner','')] + [cross_validation(a, d, k, trials) for d in datasets] for a in algorithms], header=[''] + [d.name[0:7] for d in datasets], numfmt='%.2f')
def compare(algorithms=[PluralityLearner, NaiveBayesLearner, NearestNeighborLearner, DecisionTreeLearner], datasets=[iris, orings, zoo, restaurant, SyntheticRestaurant(20), Majority(7, 100), Parity(7, 100), Xor(100)], k=10, trials=1): """Compare various learners on various datasets using cross-validation. Print results as a table.""" print_table([[a.__name__.replace('Learner','')] + [cross_validation(a, d, k, trials) for d in datasets] for a in algorithms], header=[''] + [d.name[0:7] for d in datasets], numfmt='%.2f')
[ "Compare", "various", "learners", "on", "various", "datasets", "using", "cross", "-", "validation", ".", "Print", "results", "as", "a", "table", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L672-L682
[ "def", "compare", "(", "algorithms", "=", "[", "PluralityLearner", ",", "NaiveBayesLearner", ",", "NearestNeighborLearner", ",", "DecisionTreeLearner", "]", ",", "datasets", "=", "[", "iris", ",", "orings", ",", "zoo", ",", "restaurant", ",", "SyntheticRestaurant", "(", "20", ")", ",", "Majority", "(", "7", ",", "100", ")", ",", "Parity", "(", "7", ",", "100", ")", ",", "Xor", "(", "100", ")", "]", ",", "k", "=", "10", ",", "trials", "=", "1", ")", ":", "print_table", "(", "[", "[", "a", ".", "__name__", ".", "replace", "(", "'Learner'", ",", "''", ")", "]", "+", "[", "cross_validation", "(", "a", ",", "d", ",", "k", ",", "trials", ")", "for", "d", "in", "datasets", "]", "for", "a", "in", "algorithms", "]", ",", "header", "=", "[", "''", "]", "+", "[", "d", ".", "name", "[", "0", ":", "7", "]", "for", "d", "in", "datasets", "]", ",", "numfmt", "=", "'%.2f'", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
DataSet.setproblem
Set (or change) the target and/or inputs. This way, one DataSet can be used multiple ways. inputs, if specified, is a list of attributes, or specify exclude as a list of attributes to not use in inputs. Attributes can be -n .. n, or an attrname. Also computes the list of possible values, if that wasn't done yet.
aima/learning.py
def setproblem(self, target, inputs=None, exclude=()): """Set (or change) the target and/or inputs. This way, one DataSet can be used multiple ways. inputs, if specified, is a list of attributes, or specify exclude as a list of attributes to not use in inputs. Attributes can be -n .. n, or an attrname. Also computes the list of possible values, if that wasn't done yet.""" self.target = self.attrnum(target) exclude = map(self.attrnum, exclude) if inputs: self.inputs = removeall(self.target, inputs) else: self.inputs = [a for a in self.attrs if a != self.target and a not in exclude] if not self.values: self.values = map(unique, zip(*self.examples)) self.check_me()
def setproblem(self, target, inputs=None, exclude=()): """Set (or change) the target and/or inputs. This way, one DataSet can be used multiple ways. inputs, if specified, is a list of attributes, or specify exclude as a list of attributes to not use in inputs. Attributes can be -n .. n, or an attrname. Also computes the list of possible values, if that wasn't done yet.""" self.target = self.attrnum(target) exclude = map(self.attrnum, exclude) if inputs: self.inputs = removeall(self.target, inputs) else: self.inputs = [a for a in self.attrs if a != self.target and a not in exclude] if not self.values: self.values = map(unique, zip(*self.examples)) self.check_me()
[ "Set", "(", "or", "change", ")", "the", "target", "and", "/", "or", "inputs", ".", "This", "way", "one", "DataSet", "can", "be", "used", "multiple", "ways", ".", "inputs", "if", "specified", "is", "a", "list", "of", "attributes", "or", "specify", "exclude", "as", "a", "list", "of", "attributes", "to", "not", "use", "in", "inputs", ".", "Attributes", "can", "be", "-", "n", "..", "n", "or", "an", "attrname", ".", "Also", "computes", "the", "list", "of", "possible", "values", "if", "that", "wasn", "t", "done", "yet", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L74-L89
[ "def", "setproblem", "(", "self", ",", "target", ",", "inputs", "=", "None", ",", "exclude", "=", "(", ")", ")", ":", "self", ".", "target", "=", "self", ".", "attrnum", "(", "target", ")", "exclude", "=", "map", "(", "self", ".", "attrnum", ",", "exclude", ")", "if", "inputs", ":", "self", ".", "inputs", "=", "removeall", "(", "self", ".", "target", ",", "inputs", ")", "else", ":", "self", ".", "inputs", "=", "[", "a", "for", "a", "in", "self", ".", "attrs", "if", "a", "!=", "self", ".", "target", "and", "a", "not", "in", "exclude", "]", "if", "not", "self", ".", "values", ":", "self", ".", "values", "=", "map", "(", "unique", ",", "zip", "(", "*", "self", ".", "examples", ")", ")", "self", ".", "check_me", "(", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
DataSet.check_me
Check that my fields make sense.
aima/learning.py
def check_me(self): "Check that my fields make sense." assert len(self.attrnames) == len(self.attrs) assert self.target in self.attrs assert self.target not in self.inputs assert set(self.inputs).issubset(set(self.attrs)) map(self.check_example, self.examples)
def check_me(self): "Check that my fields make sense." assert len(self.attrnames) == len(self.attrs) assert self.target in self.attrs assert self.target not in self.inputs assert set(self.inputs).issubset(set(self.attrs)) map(self.check_example, self.examples)
[ "Check", "that", "my", "fields", "make", "sense", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L91-L97
[ "def", "check_me", "(", "self", ")", ":", "assert", "len", "(", "self", ".", "attrnames", ")", "==", "len", "(", "self", ".", "attrs", ")", "assert", "self", ".", "target", "in", "self", ".", "attrs", "assert", "self", ".", "target", "not", "in", "self", ".", "inputs", "assert", "set", "(", "self", ".", "inputs", ")", ".", "issubset", "(", "set", "(", "self", ".", "attrs", ")", ")", "map", "(", "self", ".", "check_example", ",", "self", ".", "examples", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
DataSet.add_example
Add an example to the list of examples, checking it first.
aima/learning.py
def add_example(self, example): "Add an example to the list of examples, checking it first." self.check_example(example) self.examples.append(example)
def add_example(self, example): "Add an example to the list of examples, checking it first." self.check_example(example) self.examples.append(example)
[ "Add", "an", "example", "to", "the", "list", "of", "examples", "checking", "it", "first", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L99-L102
[ "def", "add_example", "(", "self", ",", "example", ")", ":", "self", ".", "check_example", "(", "example", ")", "self", ".", "examples", ".", "append", "(", "example", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
DataSet.check_example
Raise ValueError if example has any invalid values.
aima/learning.py
def check_example(self, example): "Raise ValueError if example has any invalid values." if self.values: for a in self.attrs: if example[a] not in self.values[a]: raise ValueError('Bad value %s for attribute %s in %s' % (example[a], self.attrnames[a], example))
def check_example(self, example): "Raise ValueError if example has any invalid values." if self.values: for a in self.attrs: if example[a] not in self.values[a]: raise ValueError('Bad value %s for attribute %s in %s' % (example[a], self.attrnames[a], example))
[ "Raise", "ValueError", "if", "example", "has", "any", "invalid", "values", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L104-L110
[ "def", "check_example", "(", "self", ",", "example", ")", ":", "if", "self", ".", "values", ":", "for", "a", "in", "self", ".", "attrs", ":", "if", "example", "[", "a", "]", "not", "in", "self", ".", "values", "[", "a", "]", ":", "raise", "ValueError", "(", "'Bad value %s for attribute %s in %s'", "%", "(", "example", "[", "a", "]", ",", "self", ".", "attrnames", "[", "a", "]", ",", "example", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
DataSet.attrnum
Returns the number used for attr, which can be a name, or -n .. n-1.
aima/learning.py
def attrnum(self, attr): "Returns the number used for attr, which can be a name, or -n .. n-1." if attr < 0: return len(self.attrs) + attr elif isinstance(attr, str): return self.attrnames.index(attr) else: return attr
def attrnum(self, attr): "Returns the number used for attr, which can be a name, or -n .. n-1." if attr < 0: return len(self.attrs) + attr elif isinstance(attr, str): return self.attrnames.index(attr) else: return attr
[ "Returns", "the", "number", "used", "for", "attr", "which", "can", "be", "a", "name", "or", "-", "n", "..", "n", "-", "1", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L112-L119
[ "def", "attrnum", "(", "self", ",", "attr", ")", ":", "if", "attr", "<", "0", ":", "return", "len", "(", "self", ".", "attrs", ")", "+", "attr", "elif", "isinstance", "(", "attr", ",", "str", ")", ":", "return", "self", ".", "attrnames", ".", "index", "(", "attr", ")", "else", ":", "return", "attr" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
DataSet.sanitize
Return a copy of example, with non-input attributes replaced by None.
aima/learning.py
def sanitize(self, example): "Return a copy of example, with non-input attributes replaced by None." return [attr_i if i in self.inputs else None for i, attr_i in enumerate(example)]
def sanitize(self, example): "Return a copy of example, with non-input attributes replaced by None." return [attr_i if i in self.inputs else None for i, attr_i in enumerate(example)]
[ "Return", "a", "copy", "of", "example", "with", "non", "-", "input", "attributes", "replaced", "by", "None", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L121-L124
[ "def", "sanitize", "(", "self", ",", "example", ")", ":", "return", "[", "attr_i", "if", "i", "in", "self", ".", "inputs", "else", "None", "for", "i", ",", "attr_i", "in", "enumerate", "(", "example", ")", "]" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
CountingProbDist.add
Add an observation o to the distribution.
aima/learning.py
def add(self, o): "Add an observation o to the distribution." self.smooth_for(o) self.dictionary[o] += 1 self.n_obs += 1 self.sampler = None
def add(self, o): "Add an observation o to the distribution." self.smooth_for(o) self.dictionary[o] += 1 self.n_obs += 1 self.sampler = None
[ "Add", "an", "observation", "o", "to", "the", "distribution", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L161-L166
[ "def", "add", "(", "self", ",", "o", ")", ":", "self", ".", "smooth_for", "(", "o", ")", "self", ".", "dictionary", "[", "o", "]", "+=", "1", "self", ".", "n_obs", "+=", "1", "self", ".", "sampler", "=", "None" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
CountingProbDist.smooth_for
Include o among the possible observations, whether or not it's been observed yet.
aima/learning.py
def smooth_for(self, o): """Include o among the possible observations, whether or not it's been observed yet.""" if o not in self.dictionary: self.dictionary[o] = self.default self.n_obs += self.default self.sampler = None
def smooth_for(self, o): """Include o among the possible observations, whether or not it's been observed yet.""" if o not in self.dictionary: self.dictionary[o] = self.default self.n_obs += self.default self.sampler = None
[ "Include", "o", "among", "the", "possible", "observations", "whether", "or", "not", "it", "s", "been", "observed", "yet", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L168-L174
[ "def", "smooth_for", "(", "self", ",", "o", ")", ":", "if", "o", "not", "in", "self", ".", "dictionary", ":", "self", ".", "dictionary", "[", "o", "]", "=", "self", ".", "default", "self", ".", "n_obs", "+=", "self", ".", "default", "self", ".", "sampler", "=", "None" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
CountingProbDist.top
Return (count, obs) tuples for the n most frequent observations.
aima/learning.py
def top(self, n): "Return (count, obs) tuples for the n most frequent observations." return heapq.nlargest(n, [(v, k) for (k, v) in self.dictionary.items()])
def top(self, n): "Return (count, obs) tuples for the n most frequent observations." return heapq.nlargest(n, [(v, k) for (k, v) in self.dictionary.items()])
[ "Return", "(", "count", "obs", ")", "tuples", "for", "the", "n", "most", "frequent", "observations", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L183-L185
[ "def", "top", "(", "self", ",", "n", ")", ":", "return", "heapq", ".", "nlargest", "(", "n", ",", "[", "(", "v", ",", "k", ")", "for", "(", "k", ",", "v", ")", "in", "self", ".", "dictionary", ".", "items", "(", ")", "]", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
CountingProbDist.sample
Return a random sample from the distribution.
aima/learning.py
def sample(self): "Return a random sample from the distribution." if self.sampler is None: self.sampler = weighted_sampler(self.dictionary.keys(), self.dictionary.values()) return self.sampler()
def sample(self): "Return a random sample from the distribution." if self.sampler is None: self.sampler = weighted_sampler(self.dictionary.keys(), self.dictionary.values()) return self.sampler()
[ "Return", "a", "random", "sample", "from", "the", "distribution", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L187-L192
[ "def", "sample", "(", "self", ")", ":", "if", "self", ".", "sampler", "is", "None", ":", "self", ".", "sampler", "=", "weighted_sampler", "(", "self", ".", "dictionary", ".", "keys", "(", ")", ",", "self", ".", "dictionary", ".", "values", "(", ")", ")", "return", "self", ".", "sampler", "(", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
AC3
[Fig. 6.3]
aima/csp.py
def AC3(csp, queue=None, removals=None): """[Fig. 6.3]""" if queue is None: queue = [(Xi, Xk) for Xi in csp.vars for Xk in csp.neighbors[Xi]] csp.support_pruning() while queue: (Xi, Xj) = queue.pop() if revise(csp, Xi, Xj, removals): if not csp.curr_domains[Xi]: return False for Xk in csp.neighbors[Xi]: if Xk != Xi: queue.append((Xk, Xi)) return True
def AC3(csp, queue=None, removals=None): """[Fig. 6.3]""" if queue is None: queue = [(Xi, Xk) for Xi in csp.vars for Xk in csp.neighbors[Xi]] csp.support_pruning() while queue: (Xi, Xj) = queue.pop() if revise(csp, Xi, Xj, removals): if not csp.curr_domains[Xi]: return False for Xk in csp.neighbors[Xi]: if Xk != Xi: queue.append((Xk, Xi)) return True
[ "[", "Fig", ".", "6", ".", "3", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L148-L161
[ "def", "AC3", "(", "csp", ",", "queue", "=", "None", ",", "removals", "=", "None", ")", ":", "if", "queue", "is", "None", ":", "queue", "=", "[", "(", "Xi", ",", "Xk", ")", "for", "Xi", "in", "csp", ".", "vars", "for", "Xk", "in", "csp", ".", "neighbors", "[", "Xi", "]", "]", "csp", ".", "support_pruning", "(", ")", "while", "queue", ":", "(", "Xi", ",", "Xj", ")", "=", "queue", ".", "pop", "(", ")", "if", "revise", "(", "csp", ",", "Xi", ",", "Xj", ",", "removals", ")", ":", "if", "not", "csp", ".", "curr_domains", "[", "Xi", "]", ":", "return", "False", "for", "Xk", "in", "csp", ".", "neighbors", "[", "Xi", "]", ":", "if", "Xk", "!=", "Xi", ":", "queue", ".", "append", "(", "(", "Xk", ",", "Xi", ")", ")", "return", "True" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
revise
Return true if we remove a value.
aima/csp.py
def revise(csp, Xi, Xj, removals): "Return true if we remove a value." revised = False for x in csp.curr_domains[Xi][:]: # If Xi=x conflicts with Xj=y for every possible y, eliminate Xi=x if every(lambda y: not csp.constraints(Xi, x, Xj, y), csp.curr_domains[Xj]): csp.prune(Xi, x, removals) revised = True return revised
def revise(csp, Xi, Xj, removals): "Return true if we remove a value." revised = False for x in csp.curr_domains[Xi][:]: # If Xi=x conflicts with Xj=y for every possible y, eliminate Xi=x if every(lambda y: not csp.constraints(Xi, x, Xj, y), csp.curr_domains[Xj]): csp.prune(Xi, x, removals) revised = True return revised
[ "Return", "true", "if", "we", "remove", "a", "value", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L163-L172
[ "def", "revise", "(", "csp", ",", "Xi", ",", "Xj", ",", "removals", ")", ":", "revised", "=", "False", "for", "x", "in", "csp", ".", "curr_domains", "[", "Xi", "]", "[", ":", "]", ":", "# If Xi=x conflicts with Xj=y for every possible y, eliminate Xi=x", "if", "every", "(", "lambda", "y", ":", "not", "csp", ".", "constraints", "(", "Xi", ",", "x", ",", "Xj", ",", "y", ")", ",", "csp", ".", "curr_domains", "[", "Xj", "]", ")", ":", "csp", ".", "prune", "(", "Xi", ",", "x", ",", "removals", ")", "revised", "=", "True", "return", "revised" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
mrv
Minimum-remaining-values heuristic.
aima/csp.py
def mrv(assignment, csp): "Minimum-remaining-values heuristic." return argmin_random_tie( [v for v in csp.vars if v not in assignment], lambda var: num_legal_values(csp, var, assignment))
def mrv(assignment, csp): "Minimum-remaining-values heuristic." return argmin_random_tie( [v for v in csp.vars if v not in assignment], lambda var: num_legal_values(csp, var, assignment))
[ "Minimum", "-", "remaining", "-", "values", "heuristic", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L183-L187
[ "def", "mrv", "(", "assignment", ",", "csp", ")", ":", "return", "argmin_random_tie", "(", "[", "v", "for", "v", "in", "csp", ".", "vars", "if", "v", "not", "in", "assignment", "]", ",", "lambda", "var", ":", "num_legal_values", "(", "csp", ",", "var", ",", "assignment", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
lcv
Least-constraining-values heuristic.
aima/csp.py
def lcv(var, assignment, csp): "Least-constraining-values heuristic." return sorted(csp.choices(var), key=lambda val: csp.nconflicts(var, val, assignment))
def lcv(var, assignment, csp): "Least-constraining-values heuristic." return sorted(csp.choices(var), key=lambda val: csp.nconflicts(var, val, assignment))
[ "Least", "-", "constraining", "-", "values", "heuristic", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L202-L205
[ "def", "lcv", "(", "var", ",", "assignment", ",", "csp", ")", ":", "return", "sorted", "(", "csp", ".", "choices", "(", "var", ")", ",", "key", "=", "lambda", "val", ":", "csp", ".", "nconflicts", "(", "var", ",", "val", ",", "assignment", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
forward_checking
Prune neighbor values inconsistent with var=value.
aima/csp.py
def forward_checking(csp, var, value, assignment, removals): "Prune neighbor values inconsistent with var=value." for B in csp.neighbors[var]: if B not in assignment: for b in csp.curr_domains[B][:]: if not csp.constraints(var, value, B, b): csp.prune(B, b, removals) if not csp.curr_domains[B]: return False return True
def forward_checking(csp, var, value, assignment, removals): "Prune neighbor values inconsistent with var=value." for B in csp.neighbors[var]: if B not in assignment: for b in csp.curr_domains[B][:]: if not csp.constraints(var, value, B, b): csp.prune(B, b, removals) if not csp.curr_domains[B]: return False return True
[ "Prune", "neighbor", "values", "inconsistent", "with", "var", "=", "value", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L212-L221
[ "def", "forward_checking", "(", "csp", ",", "var", ",", "value", ",", "assignment", ",", "removals", ")", ":", "for", "B", "in", "csp", ".", "neighbors", "[", "var", "]", ":", "if", "B", "not", "in", "assignment", ":", "for", "b", "in", "csp", ".", "curr_domains", "[", "B", "]", "[", ":", "]", ":", "if", "not", "csp", ".", "constraints", "(", "var", ",", "value", ",", "B", ",", "b", ")", ":", "csp", ".", "prune", "(", "B", ",", "b", ",", "removals", ")", "if", "not", "csp", ".", "curr_domains", "[", "B", "]", ":", "return", "False", "return", "True" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
mac
Maintain arc consistency.
aima/csp.py
def mac(csp, var, value, assignment, removals): "Maintain arc consistency." return AC3(csp, [(X, var) for X in csp.neighbors[var]], removals)
def mac(csp, var, value, assignment, removals): "Maintain arc consistency." return AC3(csp, [(X, var) for X in csp.neighbors[var]], removals)
[ "Maintain", "arc", "consistency", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L223-L225
[ "def", "mac", "(", "csp", ",", "var", ",", "value", ",", "assignment", ",", "removals", ")", ":", "return", "AC3", "(", "csp", ",", "[", "(", "X", ",", "var", ")", "for", "X", "in", "csp", ".", "neighbors", "[", "var", "]", "]", ",", "removals", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
backtracking_search
[Fig. 6.5] >>> backtracking_search(australia) is not None True >>> backtracking_search(australia, select_unassigned_variable=mrv) is not None True >>> backtracking_search(australia, order_domain_values=lcv) is not None True >>> backtracking_search(australia, select_unassigned_variable=mrv, order_domain_values=lcv) is not None True >>> backtracking_search(australia, inference=forward_checking) is not None True >>> backtracking_search(australia, inference=mac) is not None True >>> backtracking_search(usa, select_unassigned_variable=mrv, order_domain_values=lcv, inference=mac) is not None True
aima/csp.py
def backtracking_search(csp, select_unassigned_variable = first_unassigned_variable, order_domain_values = unordered_domain_values, inference = no_inference): """[Fig. 6.5] >>> backtracking_search(australia) is not None True >>> backtracking_search(australia, select_unassigned_variable=mrv) is not None True >>> backtracking_search(australia, order_domain_values=lcv) is not None True >>> backtracking_search(australia, select_unassigned_variable=mrv, order_domain_values=lcv) is not None True >>> backtracking_search(australia, inference=forward_checking) is not None True >>> backtracking_search(australia, inference=mac) is not None True >>> backtracking_search(usa, select_unassigned_variable=mrv, order_domain_values=lcv, inference=mac) is not None True """ def backtrack(assignment): if len(assignment) == len(csp.vars): return assignment var = select_unassigned_variable(assignment, csp) for value in order_domain_values(var, assignment, csp): if 0 == csp.nconflicts(var, value, assignment): csp.assign(var, value, assignment) removals = csp.suppose(var, value) if inference(csp, var, value, assignment, removals): result = backtrack(assignment) if result is not None: return result csp.restore(removals) csp.unassign(var, assignment) return None result = backtrack({}) assert result is None or csp.goal_test(result) return result
def backtracking_search(csp, select_unassigned_variable = first_unassigned_variable, order_domain_values = unordered_domain_values, inference = no_inference): """[Fig. 6.5] >>> backtracking_search(australia) is not None True >>> backtracking_search(australia, select_unassigned_variable=mrv) is not None True >>> backtracking_search(australia, order_domain_values=lcv) is not None True >>> backtracking_search(australia, select_unassigned_variable=mrv, order_domain_values=lcv) is not None True >>> backtracking_search(australia, inference=forward_checking) is not None True >>> backtracking_search(australia, inference=mac) is not None True >>> backtracking_search(usa, select_unassigned_variable=mrv, order_domain_values=lcv, inference=mac) is not None True """ def backtrack(assignment): if len(assignment) == len(csp.vars): return assignment var = select_unassigned_variable(assignment, csp) for value in order_domain_values(var, assignment, csp): if 0 == csp.nconflicts(var, value, assignment): csp.assign(var, value, assignment) removals = csp.suppose(var, value) if inference(csp, var, value, assignment, removals): result = backtrack(assignment) if result is not None: return result csp.restore(removals) csp.unassign(var, assignment) return None result = backtrack({}) assert result is None or csp.goal_test(result) return result
[ "[", "Fig", ".", "6", ".", "5", "]", ">>>", "backtracking_search", "(", "australia", ")", "is", "not", "None", "True", ">>>", "backtracking_search", "(", "australia", "select_unassigned_variable", "=", "mrv", ")", "is", "not", "None", "True", ">>>", "backtracking_search", "(", "australia", "order_domain_values", "=", "lcv", ")", "is", "not", "None", "True", ">>>", "backtracking_search", "(", "australia", "select_unassigned_variable", "=", "mrv", "order_domain_values", "=", "lcv", ")", "is", "not", "None", "True", ">>>", "backtracking_search", "(", "australia", "inference", "=", "forward_checking", ")", "is", "not", "None", "True", ">>>", "backtracking_search", "(", "australia", "inference", "=", "mac", ")", "is", "not", "None", "True", ">>>", "backtracking_search", "(", "usa", "select_unassigned_variable", "=", "mrv", "order_domain_values", "=", "lcv", "inference", "=", "mac", ")", "is", "not", "None", "True" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L229-L268
[ "def", "backtracking_search", "(", "csp", ",", "select_unassigned_variable", "=", "first_unassigned_variable", ",", "order_domain_values", "=", "unordered_domain_values", ",", "inference", "=", "no_inference", ")", ":", "def", "backtrack", "(", "assignment", ")", ":", "if", "len", "(", "assignment", ")", "==", "len", "(", "csp", ".", "vars", ")", ":", "return", "assignment", "var", "=", "select_unassigned_variable", "(", "assignment", ",", "csp", ")", "for", "value", "in", "order_domain_values", "(", "var", ",", "assignment", ",", "csp", ")", ":", "if", "0", "==", "csp", ".", "nconflicts", "(", "var", ",", "value", ",", "assignment", ")", ":", "csp", ".", "assign", "(", "var", ",", "value", ",", "assignment", ")", "removals", "=", "csp", ".", "suppose", "(", "var", ",", "value", ")", "if", "inference", "(", "csp", ",", "var", ",", "value", ",", "assignment", ",", "removals", ")", ":", "result", "=", "backtrack", "(", "assignment", ")", "if", "result", "is", "not", "None", ":", "return", "result", "csp", ".", "restore", "(", "removals", ")", "csp", ".", "unassign", "(", "var", ",", "assignment", ")", "return", "None", "result", "=", "backtrack", "(", "{", "}", ")", "assert", "result", "is", "None", "or", "csp", ".", "goal_test", "(", "result", ")", "return", "result" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
min_conflicts
Solve a CSP by stochastic hillclimbing on the number of conflicts.
aima/csp.py
def min_conflicts(csp, max_steps=100000): """Solve a CSP by stochastic hillclimbing on the number of conflicts.""" # Generate a complete assignment for all vars (probably with conflicts) csp.current = current = {} for var in csp.vars: val = min_conflicts_value(csp, var, current) csp.assign(var, val, current) # Now repeatedly choose a random conflicted variable and change it for i in range(max_steps): conflicted = csp.conflicted_vars(current) if not conflicted: return current var = random.choice(conflicted) val = min_conflicts_value(csp, var, current) csp.assign(var, val, current) return None
def min_conflicts(csp, max_steps=100000): """Solve a CSP by stochastic hillclimbing on the number of conflicts.""" # Generate a complete assignment for all vars (probably with conflicts) csp.current = current = {} for var in csp.vars: val = min_conflicts_value(csp, var, current) csp.assign(var, val, current) # Now repeatedly choose a random conflicted variable and change it for i in range(max_steps): conflicted = csp.conflicted_vars(current) if not conflicted: return current var = random.choice(conflicted) val = min_conflicts_value(csp, var, current) csp.assign(var, val, current) return None
[ "Solve", "a", "CSP", "by", "stochastic", "hillclimbing", "on", "the", "number", "of", "conflicts", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L273-L288
[ "def", "min_conflicts", "(", "csp", ",", "max_steps", "=", "100000", ")", ":", "# Generate a complete assignment for all vars (probably with conflicts)", "csp", ".", "current", "=", "current", "=", "{", "}", "for", "var", "in", "csp", ".", "vars", ":", "val", "=", "min_conflicts_value", "(", "csp", ",", "var", ",", "current", ")", "csp", ".", "assign", "(", "var", ",", "val", ",", "current", ")", "# Now repeatedly choose a random conflicted variable and change it", "for", "i", "in", "range", "(", "max_steps", ")", ":", "conflicted", "=", "csp", ".", "conflicted_vars", "(", "current", ")", "if", "not", "conflicted", ":", "return", "current", "var", "=", "random", ".", "choice", "(", "conflicted", ")", "val", "=", "min_conflicts_value", "(", "csp", ",", "var", ",", "current", ")", "csp", ".", "assign", "(", "var", ",", "val", ",", "current", ")", "return", "None" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
min_conflicts_value
Return the value that will give var the least number of conflicts. If there is a tie, choose at random.
aima/csp.py
def min_conflicts_value(csp, var, current): """Return the value that will give var the least number of conflicts. If there is a tie, choose at random.""" return argmin_random_tie(csp.domains[var], lambda val: csp.nconflicts(var, val, current))
def min_conflicts_value(csp, var, current): """Return the value that will give var the least number of conflicts. If there is a tie, choose at random.""" return argmin_random_tie(csp.domains[var], lambda val: csp.nconflicts(var, val, current))
[ "Return", "the", "value", "that", "will", "give", "var", "the", "least", "number", "of", "conflicts", ".", "If", "there", "is", "a", "tie", "choose", "at", "random", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L290-L294
[ "def", "min_conflicts_value", "(", "csp", ",", "var", ",", "current", ")", ":", "return", "argmin_random_tie", "(", "csp", ".", "domains", "[", "var", "]", ",", "lambda", "val", ":", "csp", ".", "nconflicts", "(", "var", ",", "val", ",", "current", ")", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
tree_csp_solver
[Fig. 6.11]
aima/csp.py
def tree_csp_solver(csp): "[Fig. 6.11]" n = len(csp.vars) assignment = {} root = csp.vars[0] X, parent = topological_sort(csp.vars, root) for Xj in reversed(X): if not make_arc_consistent(parent[Xj], Xj, csp): return None for Xi in X: if not csp.curr_domains[Xi]: return None assignment[Xi] = csp.curr_domains[Xi][0] return assignment
def tree_csp_solver(csp): "[Fig. 6.11]" n = len(csp.vars) assignment = {} root = csp.vars[0] X, parent = topological_sort(csp.vars, root) for Xj in reversed(X): if not make_arc_consistent(parent[Xj], Xj, csp): return None for Xi in X: if not csp.curr_domains[Xi]: return None assignment[Xi] = csp.curr_domains[Xi][0] return assignment
[ "[", "Fig", ".", "6", ".", "11", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L298-L311
[ "def", "tree_csp_solver", "(", "csp", ")", ":", "n", "=", "len", "(", "csp", ".", "vars", ")", "assignment", "=", "{", "}", "root", "=", "csp", ".", "vars", "[", "0", "]", "X", ",", "parent", "=", "topological_sort", "(", "csp", ".", "vars", ",", "root", ")", "for", "Xj", "in", "reversed", "(", "X", ")", ":", "if", "not", "make_arc_consistent", "(", "parent", "[", "Xj", "]", ",", "Xj", ",", "csp", ")", ":", "return", "None", "for", "Xi", "in", "X", ":", "if", "not", "csp", ".", "curr_domains", "[", "Xi", "]", ":", "return", "None", "assignment", "[", "Xi", "]", "=", "csp", ".", "curr_domains", "[", "Xi", "]", "[", "0", "]", "return", "assignment" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
MapColoringCSP
Make a CSP for the problem of coloring a map with different colors for any two adjacent regions. Arguments are a list of colors, and a dict of {region: [neighbor,...]} entries. This dict may also be specified as a string of the form defined by parse_neighbors.
aima/csp.py
def MapColoringCSP(colors, neighbors): """Make a CSP for the problem of coloring a map with different colors for any two adjacent regions. Arguments are a list of colors, and a dict of {region: [neighbor,...]} entries. This dict may also be specified as a string of the form defined by parse_neighbors.""" if isinstance(neighbors, str): neighbors = parse_neighbors(neighbors) return CSP(neighbors.keys(), UniversalDict(colors), neighbors, different_values_constraint)
def MapColoringCSP(colors, neighbors): """Make a CSP for the problem of coloring a map with different colors for any two adjacent regions. Arguments are a list of colors, and a dict of {region: [neighbor,...]} entries. This dict may also be specified as a string of the form defined by parse_neighbors.""" if isinstance(neighbors, str): neighbors = parse_neighbors(neighbors) return CSP(neighbors.keys(), UniversalDict(colors), neighbors, different_values_constraint)
[ "Make", "a", "CSP", "for", "the", "problem", "of", "coloring", "a", "map", "with", "different", "colors", "for", "any", "two", "adjacent", "regions", ".", "Arguments", "are", "a", "list", "of", "colors", "and", "a", "dict", "of", "{", "region", ":", "[", "neighbor", "...", "]", "}", "entries", ".", "This", "dict", "may", "also", "be", "specified", "as", "a", "string", "of", "the", "form", "defined", "by", "parse_neighbors", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L337-L345
[ "def", "MapColoringCSP", "(", "colors", ",", "neighbors", ")", ":", "if", "isinstance", "(", "neighbors", ",", "str", ")", ":", "neighbors", "=", "parse_neighbors", "(", "neighbors", ")", "return", "CSP", "(", "neighbors", ".", "keys", "(", ")", ",", "UniversalDict", "(", "colors", ")", ",", "neighbors", ",", "different_values_constraint", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
parse_neighbors
Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping regions to neighbors. The syntax is a region name followed by a ':' followed by zero or more region names, followed by ';', repeated for each region name. If you say 'X: Y' you don't need 'Y: X'. >>> parse_neighbors('X: Y Z; Y: Z') {'Y': ['X', 'Z'], 'X': ['Y', 'Z'], 'Z': ['X', 'Y']}
aima/csp.py
def parse_neighbors(neighbors, vars=[]): """Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping regions to neighbors. The syntax is a region name followed by a ':' followed by zero or more region names, followed by ';', repeated for each region name. If you say 'X: Y' you don't need 'Y: X'. >>> parse_neighbors('X: Y Z; Y: Z') {'Y': ['X', 'Z'], 'X': ['Y', 'Z'], 'Z': ['X', 'Y']} """ dict = DefaultDict([]) for var in vars: dict[var] = [] specs = [spec.split(':') for spec in neighbors.split(';')] for (A, Aneighbors) in specs: A = A.strip() dict.setdefault(A, []) for B in Aneighbors.split(): dict[A].append(B) dict[B].append(A) return dict
def parse_neighbors(neighbors, vars=[]): """Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping regions to neighbors. The syntax is a region name followed by a ':' followed by zero or more region names, followed by ';', repeated for each region name. If you say 'X: Y' you don't need 'Y: X'. >>> parse_neighbors('X: Y Z; Y: Z') {'Y': ['X', 'Z'], 'X': ['Y', 'Z'], 'Z': ['X', 'Y']} """ dict = DefaultDict([]) for var in vars: dict[var] = [] specs = [spec.split(':') for spec in neighbors.split(';')] for (A, Aneighbors) in specs: A = A.strip() dict.setdefault(A, []) for B in Aneighbors.split(): dict[A].append(B) dict[B].append(A) return dict
[ "Convert", "a", "string", "of", "the", "form", "X", ":", "Y", "Z", ";", "Y", ":", "Z", "into", "a", "dict", "mapping", "regions", "to", "neighbors", ".", "The", "syntax", "is", "a", "region", "name", "followed", "by", "a", ":", "followed", "by", "zero", "or", "more", "region", "names", "followed", "by", ";", "repeated", "for", "each", "region", "name", ".", "If", "you", "say", "X", ":", "Y", "you", "don", "t", "need", "Y", ":", "X", ".", ">>>", "parse_neighbors", "(", "X", ":", "Y", "Z", ";", "Y", ":", "Z", ")", "{", "Y", ":", "[", "X", "Z", "]", "X", ":", "[", "Y", "Z", "]", "Z", ":", "[", "X", "Y", "]", "}" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L347-L365
[ "def", "parse_neighbors", "(", "neighbors", ",", "vars", "=", "[", "]", ")", ":", "dict", "=", "DefaultDict", "(", "[", "]", ")", "for", "var", "in", "vars", ":", "dict", "[", "var", "]", "=", "[", "]", "specs", "=", "[", "spec", ".", "split", "(", "':'", ")", "for", "spec", "in", "neighbors", ".", "split", "(", "';'", ")", "]", "for", "(", "A", ",", "Aneighbors", ")", "in", "specs", ":", "A", "=", "A", ".", "strip", "(", ")", "dict", ".", "setdefault", "(", "A", ",", "[", "]", ")", "for", "B", "in", "Aneighbors", ".", "split", "(", ")", ":", "dict", "[", "A", "]", ".", "append", "(", "B", ")", "dict", "[", "B", "]", ".", "append", "(", "A", ")", "return", "dict" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
queen_constraint
Constraint is satisfied (true) if A, B are really the same variable, or if they are not in the same row, down diagonal, or up diagonal.
aima/csp.py
def queen_constraint(A, a, B, b): """Constraint is satisfied (true) if A, B are really the same variable, or if they are not in the same row, down diagonal, or up diagonal.""" return A == B or (a != b and A + a != B + b and A - a != B - b)
def queen_constraint(A, a, B, b): """Constraint is satisfied (true) if A, B are really the same variable, or if they are not in the same row, down diagonal, or up diagonal.""" return A == B or (a != b and A + a != B + b and A - a != B - b)
[ "Constraint", "is", "satisfied", "(", "true", ")", "if", "A", "B", "are", "really", "the", "same", "variable", "or", "if", "they", "are", "not", "in", "the", "same", "row", "down", "diagonal", "or", "up", "diagonal", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L392-L395
[ "def", "queen_constraint", "(", "A", ",", "a", ",", "B", ",", "b", ")", ":", "return", "A", "==", "B", "or", "(", "a", "!=", "b", "and", "A", "+", "a", "!=", "B", "+", "b", "and", "A", "-", "a", "!=", "B", "-", "b", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
Zebra
Return an instance of the Zebra Puzzle.
aima/csp.py
def Zebra(): "Return an instance of the Zebra Puzzle." Colors = 'Red Yellow Blue Green Ivory'.split() Pets = 'Dog Fox Snails Horse Zebra'.split() Drinks = 'OJ Tea Coffee Milk Water'.split() Countries = 'Englishman Spaniard Norwegian Ukranian Japanese'.split() Smokes = 'Kools Chesterfields Winston LuckyStrike Parliaments'.split() vars = Colors + Pets + Drinks + Countries + Smokes domains = {} for var in vars: domains[var] = range(1, 6) domains['Norwegian'] = [1] domains['Milk'] = [3] neighbors = parse_neighbors("""Englishman: Red; Spaniard: Dog; Kools: Yellow; Chesterfields: Fox; Norwegian: Blue; Winston: Snails; LuckyStrike: OJ; Ukranian: Tea; Japanese: Parliaments; Kools: Horse; Coffee: Green; Green: Ivory""", vars) for type in [Colors, Pets, Drinks, Countries, Smokes]: for A in type: for B in type: if A != B: if B not in neighbors[A]: neighbors[A].append(B) if A not in neighbors[B]: neighbors[B].append(A) def zebra_constraint(A, a, B, b, recurse=0): same = (a == b) next_to = abs(a - b) == 1 if A == 'Englishman' and B == 'Red': return same if A == 'Spaniard' and B == 'Dog': return same if A == 'Chesterfields' and B == 'Fox': return next_to if A == 'Norwegian' and B == 'Blue': return next_to if A == 'Kools' and B == 'Yellow': return same if A == 'Winston' and B == 'Snails': return same if A == 'LuckyStrike' and B == 'OJ': return same if A == 'Ukranian' and B == 'Tea': return same if A == 'Japanese' and B == 'Parliaments': return same if A == 'Kools' and B == 'Horse': return next_to if A == 'Coffee' and B == 'Green': return same if A == 'Green' and B == 'Ivory': return (a - 1) == b if recurse == 0: return zebra_constraint(B, b, A, a, 1) if ((A in Colors and B in Colors) or (A in Pets and B in Pets) or (A in Drinks and B in Drinks) or (A in Countries and B in Countries) or (A in Smokes and B in Smokes)): return not same raise 'error' return CSP(vars, domains, neighbors, zebra_constraint)
def Zebra(): "Return an instance of the Zebra Puzzle." Colors = 'Red Yellow Blue Green Ivory'.split() Pets = 'Dog Fox Snails Horse Zebra'.split() Drinks = 'OJ Tea Coffee Milk Water'.split() Countries = 'Englishman Spaniard Norwegian Ukranian Japanese'.split() Smokes = 'Kools Chesterfields Winston LuckyStrike Parliaments'.split() vars = Colors + Pets + Drinks + Countries + Smokes domains = {} for var in vars: domains[var] = range(1, 6) domains['Norwegian'] = [1] domains['Milk'] = [3] neighbors = parse_neighbors("""Englishman: Red; Spaniard: Dog; Kools: Yellow; Chesterfields: Fox; Norwegian: Blue; Winston: Snails; LuckyStrike: OJ; Ukranian: Tea; Japanese: Parliaments; Kools: Horse; Coffee: Green; Green: Ivory""", vars) for type in [Colors, Pets, Drinks, Countries, Smokes]: for A in type: for B in type: if A != B: if B not in neighbors[A]: neighbors[A].append(B) if A not in neighbors[B]: neighbors[B].append(A) def zebra_constraint(A, a, B, b, recurse=0): same = (a == b) next_to = abs(a - b) == 1 if A == 'Englishman' and B == 'Red': return same if A == 'Spaniard' and B == 'Dog': return same if A == 'Chesterfields' and B == 'Fox': return next_to if A == 'Norwegian' and B == 'Blue': return next_to if A == 'Kools' and B == 'Yellow': return same if A == 'Winston' and B == 'Snails': return same if A == 'LuckyStrike' and B == 'OJ': return same if A == 'Ukranian' and B == 'Tea': return same if A == 'Japanese' and B == 'Parliaments': return same if A == 'Kools' and B == 'Horse': return next_to if A == 'Coffee' and B == 'Green': return same if A == 'Green' and B == 'Ivory': return (a - 1) == b if recurse == 0: return zebra_constraint(B, b, A, a, 1) if ((A in Colors and B in Colors) or (A in Pets and B in Pets) or (A in Drinks and B in Drinks) or (A in Countries and B in Countries) or (A in Smokes and B in Smokes)): return not same raise 'error' return CSP(vars, domains, neighbors, zebra_constraint)
[ "Return", "an", "instance", "of", "the", "Zebra", "Puzzle", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L549-L595
[ "def", "Zebra", "(", ")", ":", "Colors", "=", "'Red Yellow Blue Green Ivory'", ".", "split", "(", ")", "Pets", "=", "'Dog Fox Snails Horse Zebra'", ".", "split", "(", ")", "Drinks", "=", "'OJ Tea Coffee Milk Water'", ".", "split", "(", ")", "Countries", "=", "'Englishman Spaniard Norwegian Ukranian Japanese'", ".", "split", "(", ")", "Smokes", "=", "'Kools Chesterfields Winston LuckyStrike Parliaments'", ".", "split", "(", ")", "vars", "=", "Colors", "+", "Pets", "+", "Drinks", "+", "Countries", "+", "Smokes", "domains", "=", "{", "}", "for", "var", "in", "vars", ":", "domains", "[", "var", "]", "=", "range", "(", "1", ",", "6", ")", "domains", "[", "'Norwegian'", "]", "=", "[", "1", "]", "domains", "[", "'Milk'", "]", "=", "[", "3", "]", "neighbors", "=", "parse_neighbors", "(", "\"\"\"Englishman: Red;\n Spaniard: Dog; Kools: Yellow; Chesterfields: Fox;\n Norwegian: Blue; Winston: Snails; LuckyStrike: OJ;\n Ukranian: Tea; Japanese: Parliaments; Kools: Horse;\n Coffee: Green; Green: Ivory\"\"\"", ",", "vars", ")", "for", "type", "in", "[", "Colors", ",", "Pets", ",", "Drinks", ",", "Countries", ",", "Smokes", "]", ":", "for", "A", "in", "type", ":", "for", "B", "in", "type", ":", "if", "A", "!=", "B", ":", "if", "B", "not", "in", "neighbors", "[", "A", "]", ":", "neighbors", "[", "A", "]", ".", "append", "(", "B", ")", "if", "A", "not", "in", "neighbors", "[", "B", "]", ":", "neighbors", "[", "B", "]", ".", "append", "(", "A", ")", "def", "zebra_constraint", "(", "A", ",", "a", ",", "B", ",", "b", ",", "recurse", "=", "0", ")", ":", "same", "=", "(", "a", "==", "b", ")", "next_to", "=", "abs", "(", "a", "-", "b", ")", "==", "1", "if", "A", "==", "'Englishman'", "and", "B", "==", "'Red'", ":", "return", "same", "if", "A", "==", "'Spaniard'", "and", "B", "==", "'Dog'", ":", "return", "same", "if", "A", "==", "'Chesterfields'", "and", "B", "==", "'Fox'", ":", "return", "next_to", "if", "A", "==", "'Norwegian'", "and", "B", "==", "'Blue'", ":", "return", "next_to", "if", "A", "==", "'Kools'", "and", "B", "==", "'Yellow'", ":", "return", "same", "if", "A", "==", "'Winston'", "and", "B", "==", "'Snails'", ":", "return", "same", "if", "A", "==", "'LuckyStrike'", "and", "B", "==", "'OJ'", ":", "return", "same", "if", "A", "==", "'Ukranian'", "and", "B", "==", "'Tea'", ":", "return", "same", "if", "A", "==", "'Japanese'", "and", "B", "==", "'Parliaments'", ":", "return", "same", "if", "A", "==", "'Kools'", "and", "B", "==", "'Horse'", ":", "return", "next_to", "if", "A", "==", "'Coffee'", "and", "B", "==", "'Green'", ":", "return", "same", "if", "A", "==", "'Green'", "and", "B", "==", "'Ivory'", ":", "return", "(", "a", "-", "1", ")", "==", "b", "if", "recurse", "==", "0", ":", "return", "zebra_constraint", "(", "B", ",", "b", ",", "A", ",", "a", ",", "1", ")", "if", "(", "(", "A", "in", "Colors", "and", "B", "in", "Colors", ")", "or", "(", "A", "in", "Pets", "and", "B", "in", "Pets", ")", "or", "(", "A", "in", "Drinks", "and", "B", "in", "Drinks", ")", "or", "(", "A", "in", "Countries", "and", "B", "in", "Countries", ")", "or", "(", "A", "in", "Smokes", "and", "B", "in", "Smokes", ")", ")", ":", "return", "not", "same", "raise", "'error'", "return", "CSP", "(", "vars", ",", "domains", ",", "neighbors", ",", "zebra_constraint", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
CSP.assign
Add {var: val} to assignment; Discard the old value if any.
aima/csp.py
def assign(self, var, val, assignment): "Add {var: val} to assignment; Discard the old value if any." assignment[var] = val self.nassigns += 1
def assign(self, var, val, assignment): "Add {var: val} to assignment; Discard the old value if any." assignment[var] = val self.nassigns += 1
[ "Add", "{", "var", ":", "val", "}", "to", "assignment", ";", "Discard", "the", "old", "value", "if", "any", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L52-L55
[ "def", "assign", "(", "self", ",", "var", ",", "val", ",", "assignment", ")", ":", "assignment", "[", "var", "]", "=", "val", "self", ".", "nassigns", "+=", "1" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
CSP.nconflicts
Return the number of conflicts var=val has with other variables.
aima/csp.py
def nconflicts(self, var, val, assignment): "Return the number of conflicts var=val has with other variables." # Subclasses may implement this more efficiently def conflict(var2): return (var2 in assignment and not self.constraints(var, val, var2, assignment[var2])) return count_if(conflict, self.neighbors[var])
def nconflicts(self, var, val, assignment): "Return the number of conflicts var=val has with other variables." # Subclasses may implement this more efficiently def conflict(var2): return (var2 in assignment and not self.constraints(var, val, var2, assignment[var2])) return count_if(conflict, self.neighbors[var])
[ "Return", "the", "number", "of", "conflicts", "var", "=", "val", "has", "with", "other", "variables", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L64-L70
[ "def", "nconflicts", "(", "self", ",", "var", ",", "val", ",", "assignment", ")", ":", "# Subclasses may implement this more efficiently", "def", "conflict", "(", "var2", ")", ":", "return", "(", "var2", "in", "assignment", "and", "not", "self", ".", "constraints", "(", "var", ",", "val", ",", "var2", ",", "assignment", "[", "var2", "]", ")", ")", "return", "count_if", "(", "conflict", ",", "self", ".", "neighbors", "[", "var", "]", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
CSP.actions
Return a list of applicable actions: nonconflicting assignments to an unassigned variable.
aima/csp.py
def actions(self, state): """Return a list of applicable actions: nonconflicting assignments to an unassigned variable.""" if len(state) == len(self.vars): return [] else: assignment = dict(state) var = find_if(lambda v: v not in assignment, self.vars) return [(var, val) for val in self.domains[var] if self.nconflicts(var, val, assignment) == 0]
def actions(self, state): """Return a list of applicable actions: nonconflicting assignments to an unassigned variable.""" if len(state) == len(self.vars): return [] else: assignment = dict(state) var = find_if(lambda v: v not in assignment, self.vars) return [(var, val) for val in self.domains[var] if self.nconflicts(var, val, assignment) == 0]
[ "Return", "a", "list", "of", "applicable", "actions", ":", "nonconflicting", "assignments", "to", "an", "unassigned", "variable", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L79-L88
[ "def", "actions", "(", "self", ",", "state", ")", ":", "if", "len", "(", "state", ")", "==", "len", "(", "self", ".", "vars", ")", ":", "return", "[", "]", "else", ":", "assignment", "=", "dict", "(", "state", ")", "var", "=", "find_if", "(", "lambda", "v", ":", "v", "not", "in", "assignment", ",", "self", ".", "vars", ")", "return", "[", "(", "var", ",", "val", ")", "for", "val", "in", "self", ".", "domains", "[", "var", "]", "if", "self", ".", "nconflicts", "(", "var", ",", "val", ",", "assignment", ")", "==", "0", "]" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
CSP.support_pruning
Make sure we can prune values from domains. (We want to pay for this only if we use it.)
aima/csp.py
def support_pruning(self): """Make sure we can prune values from domains. (We want to pay for this only if we use it.)""" if self.curr_domains is None: self.curr_domains = dict((v, list(self.domains[v])) for v in self.vars)
def support_pruning(self): """Make sure we can prune values from domains. (We want to pay for this only if we use it.)""" if self.curr_domains is None: self.curr_domains = dict((v, list(self.domains[v])) for v in self.vars)
[ "Make", "sure", "we", "can", "prune", "values", "from", "domains", ".", "(", "We", "want", "to", "pay", "for", "this", "only", "if", "we", "use", "it", ".", ")" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/csp.py#L104-L109
[ "def", "support_pruning", "(", "self", ")", ":", "if", "self", ".", "curr_domains", "is", "None", ":", "self", ".", "curr_domains", "=", "dict", "(", "(", "v", ",", "list", "(", "self", ".", "domains", "[", "v", "]", ")", ")", "for", "v", "in", "self", ".", "vars", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470