Instruction:
Here you have a function in Python 3, explain what it does
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

Response: Updates the cache with setting values from the database.


Instruction:
Here you have a function in Python 3, explain what it does
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)))

Response: Given a state in a game calculate the best move by searching all the way to the terminal states. [ Fig. 5. 3 ]


Instruction:
Here you have a function in Python 3, explain what it does
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))

Response: Search game to determine best action ; use alpha - beta pruning.


Instruction:
Can you generate the documentation for the following Python 3 function
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))

Response: Play an n - person move - alternateating game.


Instruction:
How would you implement a function in Python 3 that
returns the value to player ; 1 for win - 1 for loss 0 otherwise.

Response:
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)


Instruction:
Can you generate the documentation for the following Python 3 function
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

Response: If X wins with this move return 1 ; else return - 1.


Instruction:
Given the following Python 3 function, write the documentation
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

Response: Return true if there is a line through move on board for player.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update(x, **entries):
    if isinstance(x, dict):
        x.update(entries)
    else:
        x.__dict__.update(entries)
    return x

Response: Update a dict or object with slots according to entries dict.


Instruction:
How would you code a function in Python 3 to
return a copy of seq with all occurences of item removed.

Response:
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]


Instruction:
Create a Python 3 function for
counting the number of elements of seq for which the predicate is true.

Response:
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)


Instruction:
Implement a function in Python 3 to
return True if some element of seq satisfies predicate.

Response:
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


Instruction:
Here you have a function in Python 3, explain what it does
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

Response: Return an element with lowest fn ( seq [ i ] ) score ; tie goes to first one.


Instruction:
Can you generate the documentation for the following Python 3 function
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

Response: Return a list of elements of seq with the lowest fn ( seq [ i ] scores.


Instruction:
How would you explain what the following Python 3 function does
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

Response: Return an element with lowest fn ( seq [ i ] score ; break ties at random.


Instruction:
Explain what the following Python 3 code does
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())

Response: Return a list of pairs summarizing the input values.


Instruction:
How would you code a function in Python 3 to
return the median value of the given list of values.

Response:
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)


Instruction:
Create a Python 3 function for
returning the sum of the element - wise product of vectors x and y.

Response:
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)])


Instruction:
Can you implement a function in Python 3 that
picks n samples from seq at random with replacement with the corresponding probability of each element in proportion to its corresponding weight.

Response:
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)]


Instruction:
Can you tell what is the following Python 3 function doing
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]))]

Response: Return a random - sample function that picks from seq weighted by weights.


Instruction:
Can you tell what is the following Python 3 function doing
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()

Response: Convert to a number if possible or strip it.


Instruction:
Can you create a Python 3 function that
multiplies each number by a constant such that the sum is 1. 0

Response:
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]


Instruction:
Can you generate the documentation for the following Python 3 function
def distance((ax, ay), (bx, by)):
    "The distance between two (x, y) points."
    return math.hypot((ax - bx), (ay - by))

Response: The distance between two ( x y ) points.


Instruction:
Can you tell what is the following Python 3 function doing
def vector_clip(vector, lowest, highest):
    return type(vector)(map(clip, vector, lowest, highest))

Response:
Return vector except if any element is less than the corresponding
    value of lowest or more than the corresponding
    value of highest.


Instruction:
Here you have a function in Python 3, explain what it does
def printf(format, *args):
    sys.stdout.write(str(format) % args)
    return if_(args, lambda: args[-1], lambda: format)

Response:
Format args with the first argument as format string and write.
    Return the last arg or format itself.


Instruction:
How would you code a function in Python 3 to
like C ++ and Java s if_.

Response:
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


Instruction:
Create a Python 3 function to
try to find some reasonable name for the object.

Response:
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))


Instruction:
Can you generate the documentation for the following Python 3 function
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))

Response: Print a list of lists as a table so that columns line up nicely.


Instruction:
Create a Python 3 function for
opening a file based at the AIMA root directory.

Response:
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)


Instruction:
Here you have a function in Python 3, explain what it does
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]

Response: r Convert a CSV string into a list of lists.


Instruction:
Make a summary of the following Python 3 code
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

Response: A very dumb algorithm that always pick the most popular result from the training set.


Instruction:
Here you have a function in Python 3, explain what it does
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

Response: k - NearestNeighbor : the k nearest neighbors vote.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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)

Response: Number of bits to represent the probability distribution in values.


Instruction:
Here you have a function in Python 3, explain what it does
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
        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

Response: A decision list learner that returns a list of the examples that are in the dataset.


Instruction:
Explain what the following Python 3 code does
def NeuralNetLearner(dataset, sizes):

   activations = map(lambda n: [0.0 for i in range(n)], sizes)
   weights = []

   def predict(example):
      unimplemented()

   return predict

Response: Layered feed - forward network.


Instruction:
Can you tell what is the following Python 3 function doing
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

Response: Given a list of learning algorithms have them vote.


Instruction:
Can you tell what is the following Python 3 function doing
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

Response: AdaBoost is a function that returns a weighted majority model for each of the K elements.


Instruction:
Can you create a Python 3 function that
returns a predictor that takes a weighted vote.

Response:
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


Instruction:
Can you generate the documentation for the following Python 3 function
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)

Response: Return the value with the greatest total weight.


Instruction:
Implement a Python 3 function for
returning a new unweighted learner that takes just an unweighted dataset and returns a new unweighted learner that takes also a weight for each example.

Response:
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


Instruction:
How would you code a function in Python 3 to
copy dataset replicating each example in proportion to its weight.

Response:
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


Instruction:
Write a Python 3 script for
returning n selections from seq with the count of each element of seq proportional to the corresponding weight.

Response:
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)))


Instruction:
Can you generate the documentation for the following Python 3 function
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)])

Response: Do k - fold cross_validate and return their mean.


Instruction:
Create a Python 3 function to
leave one out cross - validation over the dataset.

Response:
def leave1out(learner, dataset):
    "Leave one out cross-validation over the dataset."
    return cross_validation(learner, dataset, k=len(dataset.examples))


Instruction:
Explain what the following Python 3 code does
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)])

Response: Generate a DataSet with n examples.


Instruction:
How would you implement a function in Python 3 that
returns a DataSet with n k - bit examples of the majority problem.

Response:
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)


Instruction:
Given the following Python 3 function, write the documentation
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')

Response: Compare various learners on various datasets using cross - validation.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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()

Response: Set or change the target and inputs.


Instruction:
Explain what the following Python 3 code does
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)

Response: Check that my fields make sense.


Instruction:
Can you create a Python 3 function that
adds an example to the list of examples checking it first.

Response:
def add_example(self, example):
        "Add an example to the list of examples, checking it first."
        self.check_example(example)
        self.examples.append(example)


Instruction:
Make a summary of the following Python 3 code
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))

Response: Raise ValueError if example has any invalid values.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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

Response: Returns the number used for attr which can be a name or - n.. n - 1.


Instruction:
How would you implement a function in Python 3 that
returns a copy of example with non - input attributes replaced by None.

Response:
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)]


Instruction:
Explain what the following Python 3 code does
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

Response: Add an observation o to the distribution.


Instruction:
Can you implement a function in Python 3 that
includes o among the possible observations whether or not it s observed yet.

Response:
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


Instruction:
Can you implement a function in Python 3 that
returns ( count obs ) tuples for the n most frequent observations.

Response:
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()])


Instruction:
Here you have a function in Python 3, explain what it does
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()

Response: Return a random sample from the distribution.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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

Response: Fig. 6. 3. 1. 3. 1. 2. 2.


Instruction:
Given the following Python 3 function, write the documentation
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

Response: Return true if we remove a value.


Instruction:
Can you generate the documentation for the following Python 3 function
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))

Response: Minimum - remaining - values heuristic.


Instruction:
How would you explain what the following Python 3 function does
def lcv(var, assignment, csp):
    "Least-constraining-values heuristic."
    return sorted(csp.choices(var),
                  key=lambda val: csp.nconflicts(var, val, assignment))

Response: Least - contraining - values heuristic.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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

Response: Prune neighbor values inconsistent with var = value.


Instruction:
Given the following Python 3 function, write the documentation
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

Response: Solve a CSP by stochastic hillclimbing on the number of conflicts.


Instruction:
Write a Python 3 script for
returning the value that will give var the least number of conflicts.

Response:
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))


Instruction:
Can you tell what is the following Python 3 function doing
def MapColoringCSP(colors, neighbors):
    if isinstance(neighbors, str):
        neighbors = parse_neighbors(neighbors)
    return CSP(neighbors.keys(), UniversalDict(colors), neighbors,
               different_values_constraint)

Response: Make a CSP for the problem of coloring a map with different colors.


Instruction:
How would you code a function in Python 3 to
convert a string of the form X Y Z ; Y Z ; Z ; X Y Z ; Y Z ; Z ; X Y Z ; Y Z ; X Y Z ; Y Z Z.

Response:
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


Instruction:
Can you generate the documentation for the following Python 3 function
def queen_constraint(A, a, B, b):
    return A == B or (a != b and A + a != B + b and A - a != B - b)

Response: Constraint is satisfied if A and B are not the same variable and are not in the same row down diagonal or up diagonal.


Instruction:
Given the following Python 3 function, write the documentation
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)

Response: Return an instance of the Zebra Puzzle.


Instruction:
Given the following Python 3 function, write the documentation
def assign(self, var, val, assignment):
        "Add {var: val} to assignment; Discard the old value if any."
        assignment[var] = val
        self.nassigns += 1

Response: Add { var : val to assignment ; Discard the old value if any.


Instruction:
Write a Python 3 function for
returning the number of conflicts var = val has with other variables.

Response:
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])


Instruction:
Explain what the following Python 3 code does
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]

Response:
Return a list of applicable actions for nonconflicting
            assignments to an unassigned variable.


Instruction:
How would you implement a function in Python 3 that
makes sure we can prune values from domains.

Response:
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)


Instruction:
Make a summary of the following Python 3 code
def suppose(self, var, value):
        "Start accumulating inferences from assuming var=value."
        self.support_pruning()
        removals = [(var, a) for a in self.curr_domains[var] if a != value]
        self.curr_domains[var] = [value]
        return removals

Response: Start accumulating inferences from assuming var = value.


Instruction:
Explain what the following Python 3 code does
def prune(self, var, value, removals):
        "Rule out var=value."
        self.curr_domains[var].remove(value)
        if removals is not None: removals.append((var, value))

Response: Rule out var = value.


Instruction:
Can you create a Python 3 function that
returns the partial assignment implied by the current inferences.

Response:
def infer_assignment(self):
        "Return the partial assignment implied by the current inferences."
        self.support_pruning()
        return dict((v, self.curr_domains[v][0])
                    for v in self.vars if 1 == len(self.curr_domains[v]))


Instruction:
Can you write a function in Python 3 where it
undoes a supposition and all inferences from it.

Response:
def restore(self, removals):
        "Undo a supposition and all inferences from it."
        for B, b in removals:
            self.curr_domains[B].append(b)


Instruction:
Implement a function in Python 3 to
return a list of variables in current assignment that are in conflict

Response:
def conflicted_vars(self, current):
        "Return a list of variables in current assignment that are in conflict"
        return [var for var in self.vars
                if self.nconflicts(var, current[var], current) > 0]


Instruction:
Can you write a function in Python 3 where it
assigns var and keep track of conflicts.

Response:
def assign(self, var, val, assignment):
        "Assign var, and keep track of conflicts."
        oldval = assignment.get(var, None)
        if val != oldval:
            if oldval is not None: # Remove old val if there was one
                self.record_conflict(assignment, var, oldval, -1)
            self.record_conflict(assignment, var, val, +1)
            CSP.assign(self, var, val, assignment)


Instruction:
Make a summary of the following Python 3 code
def unassign(self, var, assignment):
        "Remove var from assignment (if it is there) and track conflicts."
        if var in assignment:
            self.record_conflict(assignment, var, assignment[var], -1)
        CSP.unassign(self, var, assignment)

Response: Remove var from assignment ( if it is there and track conflicts.


Instruction:
Here you have a function in Python 3, explain what it does
def record_conflict(self, assignment, var, val, delta):
        "Record conflicts caused by addition or deletion of a Queen."
        n = len(self.vars)
        self.rows[val] += delta
        self.downs[var + val] += delta
        self.ups[var - val + n - 1] += delta

Response: Record conflicts caused by addition or deletion of a Queen.


Instruction:
Write a Python 3 script to
print the queens and the nconflicts values ( for debugging.

Response:
def display(self, assignment):
        "Print the queens and the nconflicts values (for debugging)."
        n = len(self.vars)
        for val in range(n):
            for var in range(n):
                if assignment.get(var,'') == val: ch = 'Q'
                elif (var+val) % 2 == 0: ch = '.'
                else: ch = '-'
                print ch,
            print '    ',
            for var in range(n):
                if assignment.get(var,'') == val: ch = '*'
                else: ch = ' '
                print str(self.nconflicts(var, val, assignment))+ch,
            print


Instruction:
Write a Python 3 function that can
find the best segmentation of the string of characters given the UnigramTextModel P.

Response:
def viterbi_segment(text, P):
    """Find the best segmentation of the string of characters, given the
    UnigramTextModel P."""
    # best[i] = best probability for text[0:i]
    # words[i] = best word ending at position i
    n = len(text)
    words = [''] + list(text)
    best = [1.0] + [0.0] * n
    ## Fill in the vectors best, words via dynamic programming
    for i in range(n+1):
        for j in range(0, i):
            w = text[j:i]
            if P[w] * best[i - len(w)] >= best[i]:
                best[i] = P[w] * best[i - len(w)]
                words[i] = w
    ## Now recover the sequence of best words
    sequence = []; i = len(words)-1
    while i > 0:
        sequence[0:0] = [words[i]]
        i = i - len(words[i])
    ## Return sequence of best words and overall probability
    return sequence, best[-1]


Instruction:
Given the following Python 3 function, write the documentation
def encode(plaintext, code):
    "Encodes text, using a code which is a permutation of the alphabet."
    from string import maketrans
    trans = maketrans(alphabet + alphabet.upper(), code + code.upper())
    return plaintext.translate(trans)

Response: Encodes text using a code which is a permutation of the alphabet.


Instruction:
Implement a function in Python 3 to
count 1 for P w1... wn and for P wn - 1... wn - 1

Response:
def add(self, ngram):
        """Count 1 for P[(w1, ..., wn)] and for P(wn | (w1, ..., wn-1)"""
        CountingProbDist.add(self, ngram)
        self.cond_prob[ngram[:-1]].add(ngram[-1])


Instruction:
Create a Python 3 function to
add each of the tuple words [ i : i + n using a sliding window.

Response:
def add_sequence(self, words):
        """Add each of the tuple words[i:i+n], using a sliding window.
        Prefix some copies of the empty word, '', to make the start work."""
        n = self.n
        words = ['',] * (n-1) + words
        for i in range(len(words)-n):
            self.add(tuple(words[i:i+n]))


Instruction:
Can you implement a function in Python 3 that
builds up a random sample of text nwords words long using the conditional probability given the n - 1 preceding words.

Response:
def samples(self, nwords):
        """Build up a random sample of text nwords words long, using
        the conditional probability given the n-1 preceding words."""
        n = self.n
        nminus1gram = ('',) * (n-1)
        output = []
        for i in range(nwords):
            if nminus1gram not in self.cond_prob:
                nminus1gram = ('',) * (n-1) # Cannot continue, so restart.
            wn = self.cond_prob[nminus1gram].sample()
            output.append(wn)
            nminus1gram = nminus1gram[1:] + (wn,)
        return ' '.join(output)


Instruction:
Create a Python 3 function for
indexing a whole collection of files.

Response:
def index_collection(self, filenames):
        "Index a whole collection of files."
        for filename in filenames:
            self.index_document(open(filename).read(), filename)


Instruction:
Make a summary of the following Python 3 code
def index_document(self, text, url):
        "Index the text of a document."
        ## For now, use first line for title
        title = text[:text.index('\n')].strip()
        docwords = words(text)
        docid = len(self.documents)
        self.documents.append(Document(title, url, len(docwords)))
        for word in docwords:
            if word not in self.stopwords:
                self.index[word][docid] += 1

Response: Index the text of a document.


Instruction:
Can you tell what is the following Python 3 function doing
def query(self, query_text, n=10):
        if query_text.startswith("learn:"):
            doctext = os.popen(query_text[len("learn:"):], 'r').read()
            self.index_document(doctext, query_text)
            return []
        qwords = [w for w in words(query_text) if w not in self.stopwords]
        shortest = argmin(qwords, lambda w: len(self.index[w]))
        docs = self.index[shortest]
        results = [(sum([self.score(w, d) for w in qwords]), d) for d in docs]
        results.sort(); results.reverse()
        return results[:n]

Response: Query the database for the best matches.


Instruction:
Create a Python 3 function to
compute a score for this word on this docid.

Response:
def score(self, word, docid):
        "Compute a score for this word on this docid."
        ## There are many options; here we take a very simple approach
        return (math.log(1 + self.index[word][docid])
                / math.log(1 + self.documents[docid].nwords))


Instruction:
Here you have a function in Python 3, explain what it does
def present(self, results):
        "Present the results as a list."
        for (score, d) in results:
            doc = self.documents[d]
            print ("%5.2f|%25s | %s"
                   % (100 * score, doc.url, doc.title[:45].expandtabs()))

Response: Present the results as a list.


Instruction:
Write a Python 3 script to
get results for the query and present them.

Response:
def present_results(self, query_text, n=10):
        "Get results for the query and present them."
        self.present(self.query(query_text, n))


Instruction:
Explain what the following Python 3 code does
def score(self, plaintext):
        "Return a score for text based on how common letters pairs are."
        s = 1.0
        for bi in bigrams(plaintext):
            s = s * self.P2[bi]
        return s

Response: Return a score for text based on how common letters pairs are.


Instruction:
Implement a function in Python 3 to
search for a decoding of the ciphertext.

Response:
def decode(self, ciphertext):
        "Search for a decoding of the ciphertext."
        self.ciphertext = ciphertext
        problem = PermutationDecoderProblem(decoder=self)
        return search.best_first_tree_search(
            problem, lambda node: self.score(node.state))


Instruction:
Here you have a function in Python 3, explain what it does
def score(self, code):
        text = permutation_decode(self.ciphertext, code)
        logP = (sum([log(self.Pwords[word]) for word in words(text)]) +
                sum([log(self.P1[c]) for c in text]) +
                sum([log(self.P2[b]) for b in bigrams(text)]))
        return exp(logP)

Response: Score the code with the unigram and bigram words.


Instruction:
Can you tell what is the following Python 3 function doing
def get_value(self, context, default):
        if default is None:
            settings = self.setting_model.objects.as_dict()
        else:
            settings = self.setting_model.objects.as_dict(default=default)
        return settings

Response: Returns a dictionary representation of the object.


Instruction:
Make a summary of the following Python 3 code
def get_value(self, context, name, default):
        settings = self.setting_model.objects.filter(name=name)
        if default is None:
            settings = settings.as_dict()
        else:
            settings = settings.as_dict(default=default)
        value = settings[name]
        return value

Response: Returns the value of the named setting.


Instruction:
Write a Python 3 function for
returning the value of the named setting.

Response:
def render_tag(self, context, name, nodelist):
        """
        Returns the value of the named setting.
        """
        # Use `try` and `except` instead of `setdefault()` so we can skip
        # rendering the nodelist when the setting already exists.
        settings = self.setting_model.objects.filter(name=name).as_dict()
        try:
            value = settings[name]
        except KeyError:
            value = settings[name] = nodelist.render(context)
        return value


Instruction:
How would you explain what the following Python 3 function does
def value_iteration(mdp, epsilon=0.001):
    "Solving an MDP by value iteration. [Fig. 17.4]"
    U1 = dict([(s, 0) for s in mdp.states])
    R, T, gamma = mdp.R, mdp.T, mdp.gamma
    while True:
        U = U1.copy()
        delta = 0
        for s in mdp.states:
            U1[s] = R(s) + gamma * max([sum([p * U[s1] for (p, s1) in T(s, a)])
                                        for a in mdp.actions(s)])
            delta = max(delta, abs(U1[s] - U[s]))
        if delta < epsilon * (1 - gamma) / gamma:
             return U

Response: Solving an MDP by value iteration. [ Fig. 17. 4 ]


Instruction:
Can you create a Python 3 function that
gives an MDP and a utility function U determine the best policy for the given MDP and U.

Response:
def best_policy(mdp, U):
    """Given an MDP and a utility function U, determine the best policy,
    as a mapping from state to action. (Equation 17.4)"""
    pi = {}
    for s in mdp.states:
        pi[s] = argmax(mdp.actions(s), lambda a:expected_utility(a, s, U, mdp))
    return pi


Instruction:
How would you explain what the following Python 3 function does
def expected_utility(a, s, U, mdp):
    "The expected utility of doing a in state s, according to the MDP and U."
    return sum([p * U[s1] for (p, s1) in mdp.T(s, a)])

Response: The expected utility of doing a in state s according to the MDP and U.


Instruction:
Write a Python 3 function for
solving an MDP by policy iteration [ Fig. 17. 7 ]

Response:
def policy_iteration(mdp):
    "Solve an MDP by policy iteration [Fig. 17.7]"
    U = dict([(s, 0) for s in mdp.states])
    pi = dict([(s, random.choice(mdp.actions(s))) for s in mdp.states])
    while True:
        U = policy_evaluation(pi, U, mdp)
        unchanged = True
        for s in mdp.states:
            a = argmax(mdp.actions(s), lambda a: expected_utility(a,s,U,mdp))
            if a != pi[s]:
                pi[s] = a
                unchanged = False
        if unchanged:
            return pi


Instruction:
Can you generate the documentation for the following Python 3 function
def policy_evaluation(pi, U, mdp, k=20):
    R, T, gamma = mdp.R, mdp.T, mdp.gamma
    for i in range(k):
        for s in mdp.states:
            U[s] = R(s) + gamma * sum([p * U[s1] for (p, s1) in T(s, pi[s])])
    return U

Response:
Return an updated utility mapping U from each state in the MDP to its
    utility using an approximation.


Instruction:
Given the following Python 3 function, write the documentation
def go(self, state, direction):
        "Return the state that results from going in this direction."
        state1 = vector_add(state, direction)
        return if_(state1 in self.states, state1, state)

Response: Return the state that results from going in this direction.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_grid(self, mapping):
        return list(reversed([[mapping.get((x,y), None)
                               for x in range(self.cols)]
                              for y in range(self.rows)]))

Response: Convert a mapping from x y to v into a list of grids.


Instruction:
Here you have a function in Python 3, explain what it does
def as_dict(self, default=None):
        settings = SettingDict(queryset=self, default=default)
        return settings

Response: Returns a dictionary representation of this queryset.


Instruction:
Write a Python 3 script to
create and returns an object of the appropriate type for value.

Response:
def create(self, name, value):
        """
        Creates and returns an object of the appropriate type for ``value``.
        """
        if value is None:
            raise ValueError('Setting value cannot be `None`.')
        model = Setting.get_model_for_value(value)
        # Call `create()` method on the super class to avoid recursion.
        obj = super(SettingQuerySet, model.objects.all()) \
            .create(name=name, value=value)
        return obj


Instruction:
Write a Python 3 function that can
return the model that is compatible with the type of value.

Response:
def get_model_for_value(cls, value):
        """
        Iterates through setting value subclasses, returning one that is
        compatible with the type of ``value``. Calls ``is_compatible()`` on
        each subclass.
        """
        for related_object in get_all_related_objects(cls._meta):
            model = getattr(related_object, 'related_model', related_object.model)
            if issubclass(model, cls):
                if model.is_compatible(value):
                    return model
        raise ValueError(
            'No compatible `SettingValueModel` subclass for %r' % value)


Instruction:
Given the following Python 3 function, write the documentation
def is_compatible(cls, value):
        if not hasattr(cls, 'value_type'):
            raise NotImplementedError(
                'You must define a `value_type` attribute or override the '
                '`is_compatible()` method on `SettingValueModel` subclasses.')
        return isinstance(value, cls.value_type)

Response: Checks if value is an instance of cls. value_type.


Instruction:
Write a Python 3 function for
searching through the successors of a problem to find a goal.

Response:
def tree_search(problem, frontier):
    """Search through the successors of a problem to find a goal.
    The argument frontier should be an empty queue.
    Don't worry about repeated paths to a state. [Fig. 3.7]"""
    frontier.append(Node(problem.initial))
    while frontier:
        node = frontier.pop()
        if problem.goal_test(node.state):
            return node
        frontier.extend(node.expand(problem))
    return None


Instruction:
Create a Python 3 function to
search through the successors of a problem to find a goal.

Response:
def graph_search(problem, frontier):
    """Search through the successors of a problem to find a goal.
    The argument frontier should be an empty queue.
    If two paths reach a state, only use the first one. [Fig. 3.7]"""
    frontier.append(Node(problem.initial))
    explored = set()
    while frontier:
        node = frontier.pop()
        if problem.goal_test(node.state):
            return node
        explored.add(node.state)
        frontier.extend(child for child in node.expand(problem)
                        if child.state not in explored
                        and child not in frontier)
    return None


Instruction:
Can you implement a function in Python 3 that
searches the nodes with the lowest f scores first.

Response:
def best_first_graph_search(problem, f):
    """Search the nodes with the lowest f scores first.
    You specify the function f(node) that you want to minimize; for example,
    if f is a heuristic estimate to the goal, then we have greedy best
    first search; if f is node.depth then we have breadth-first search.
    There is a subtlety: the line "f = memoize(f, 'f')" means that the f
    values will be cached on the nodes as they are computed. So after doing
    a best first search you can examine the f values of the path returned."""
    f = memoize(f, 'f')
    node = Node(problem.initial)
    if problem.goal_test(node.state):
        return node
    frontier = PriorityQueue(min, f)
    frontier.append(node)
    explored = set()
    while frontier:
        node = frontier.pop()
        if problem.goal_test(node.state):
            return node
        explored.add(node.state)
        for child in node.expand(problem):
            if child.state not in explored and child not in frontier:
                frontier.append(child)
            elif child in frontier:
                incumbent = frontier[child]
                if f(child) < f(incumbent):
                    del frontier[incumbent]
                    frontier.append(child)
    return None


Instruction:
Make a summary of the following Python 3 code
def recursive_best_first_search(problem, h=None):
    "[Fig. 3.26]"
    h = memoize(h or problem.h, 'h')

    def RBFS(problem, node, flimit):
        if problem.goal_test(node.state):
            return node, 0   # (The second value is immaterial)
        successors = node.expand(problem)
        if len(successors) == 0:
            return None, infinity
        for s in successors:
            s.f = max(s.path_cost + h(s), node.f)
        while True:
            successors.sort(lambda x,y: cmp(x.f, y.f)) # Order by lowest f value
            best = successors[0]
            if best.f > flimit:
                return None, best.f
            if len(successors) > 1:
                alternative = successors[1].f
            else:
                alternative = infinity
            result, best.f = RBFS(problem, best, min(flimit, alternative))
            if result is not None:
                return result, best.f

    node = Node(problem.initial)
    node.f = h(node)
    result, bestf = RBFS(problem, node, infinity)
    return result

Response: Recursive function to find the best first node in the tree.


Instruction:
Explain what the following Python 3 code does
def exp_schedule(k=20, lam=0.005, limit=100):
    "One possible schedule function for simulated annealing"
    return lambda t: if_(t < limit, k * math.exp(-lam * t), 0)

Response: One possible schedule function for simulated annealing


Instruction:
Create a Python 3 function for
calling genetic_algorithm on the appropriate parts of a problem. This is a convenience function that uses the fitness_fn to compute the fitness of the problem.

Response:
def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20):
    """Call genetic_algorithm on the appropriate parts of a problem.
    This requires the problem to have states that can mate and mutate,
    plus a value method that scores states."""
    s = problem.initial_state
    states = [problem.result(s, a) for a in problem.actions(s)]
    random.shuffle(states)
    return genetic_algorithm(states[:n], problem.value, ngen, pmut)


Instruction:
Make a summary of the following Python 3 code
def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.1):
    "[Fig. 4.8]"
    for i in range(ngen):
        new_population = []
        for i in len(population):
            fitnesses = map(fitness_fn, population)
            p1, p2 = weighted_sample_with_replacement(population, fitnesses, 2)
            child = p1.mate(p2)
            if random.uniform(0, 1) < pmut:
                child.mutate()
            new_population.append(child)
        population = new_population
    return argmax(population, fitness_fn)

Response: Generate a random set of all the objects in the given population.


Instruction:
Write a Python 3 function that can
construct a random graph with the specified nodes and random links.

Response:
def RandomGraph(nodes=range(10), min_links=2, width=400, height=300,
                                curvature=lambda: random.uniform(1.1, 1.5)):
    """Construct a random graph, with the specified nodes, and random links.
    The nodes are laid out randomly on a (width x height) rectangle.
    Then each node is connected to the min_links nearest neighbors.
    Because inverse links are added, some nodes will have more connections.
    The distance between nodes is the hypotenuse times curvature(),
    where curvature() defaults to a random number between 1.1 and 1.5."""
    g = UndirectedGraph()
    g.locations = {}
    ## Build the cities
    for node in nodes:
        g.locations[node] = (random.randrange(width), random.randrange(height))
    ## Build roads from each city to at least min_links nearest neighbors.
    for i in range(min_links):
        for node in nodes:
            if len(g.get(node)) < min_links:
                here = g.locations[node]
                def distance_to_node(n):
                    if n is node or g.get(node,n): return infinity
                    return distance(g.locations[n], here)
                neighbor = argmin(nodes, distance_to_node)
                d = distance(g.locations[neighbor], here) * curvature()
                g.connect(node, neighbor, int(d))
    return g


Instruction:
Can you generate the documentation for the following Python 3 function
def random_boggle(n=4):
    cubes = [cubes16[i % 16] for i in range(n*n)]
    random.shuffle(cubes)
    return map(random.choice, cubes)

Response: Return a random Boggle board of size n x n.


Instruction:
Write a Python 3 function for
printing the board in a 2 - d array.

Response:
def print_boggle(board):
    "Print the board in a 2-d array."
    n2 = len(board); n = exact_sqrt(n2)
    for i in range(n2):
        if i % n == 0 and i > 0: print
        if board[i] == 'Q': print 'Qu',
        else: print str(board[i]) + ' ',
    print


Instruction:
Write a Python 3 script to
return a list of lists where the i - th element is the list of indexes for the neighbors of square i.

Response:
def boggle_neighbors(n2, cache={}):
    """Return a list of lists, where the i-th element is the list of indexes
    for the neighbors of square i."""
    if cache.get(n2):
        return cache.get(n2)
    n = exact_sqrt(n2)
    neighbors = [None] * n2
    for i in range(n2):
        neighbors[i] = []
        on_top = i < n
        on_bottom = i >= n2 - n
        on_left = i % n == 0
        on_right = (i+1) % n == 0
        if not on_top:
            neighbors[i].append(i - n)
            if not on_left:  neighbors[i].append(i - n - 1)
            if not on_right: neighbors[i].append(i - n + 1)
        if not on_bottom:
            neighbors[i].append(i + n)
            if not on_left:  neighbors[i].append(i + n - 1)
            if not on_right: neighbors[i].append(i + n + 1)
        if not on_left: neighbors[i].append(i - 1)
        if not on_right: neighbors[i].append(i + 1)
    cache[n2] = neighbors
    return neighbors


Instruction:
Given the following Python 3 function, write the documentation
def exact_sqrt(n2):
    "If n2 is a perfect square, return its square root, else raise error."
    n = int(math.sqrt(n2))
    assert n * n == n2
    return n

Response: If n2 is a perfect square return its square root else raise error.


Instruction:
Can you write a function in Python 3 where it
solves inverse Boggle by hill - climbing

Response:
def boggle_hill_climbing(board=None, ntimes=100, verbose=True):
    """Solve inverse Boggle by hill-climbing: find a high-scoring board by
    starting with a random one and changing it."""
    finder = BoggleFinder()
    if board is None:
        board = random_boggle()
    best = len(finder.set_board(board))
    for _ in range(ntimes):
        i, oldc = mutate_boggle(board)
        new = len(finder.set_board(board))
        if new > best:
            best = new
            if verbose: print best, _, board
        else:
            board[i] = oldc ## Change back
    if verbose:
        print_boggle(board)
    return board, best


Instruction:
Can you generate the documentation for the following Python 3 function
def compare_graph_searchers():
    compare_searchers(problems=[GraphProblem('A', 'B', romania),
                                GraphProblem('O', 'N', romania),
                                GraphProblem('Q', 'WA', australia)],
            header=['Searcher', 'Romania(A, B)', 'Romania(O, N)', 'Australia'])

Response: Prints a table of results like this


Instruction:
Implement a function in Python 3 to
list the nodes reachable in one step from this node.

Response:
def expand(self, problem):
        "List the nodes reachable in one step from this node."
        return [self.child_node(problem, action)
                for action in problem.actions(self.state)]


Instruction:
Can you tell what is the following Python 3 function doing
def path(self):
        "Return a list of nodes forming the path from the root to this node."
        node, path_back = self, []
        while node:
            path_back.append(node)
            node = node.parent
        return list(reversed(path_back))

Response: Return a list of nodes forming the path from the root to this node.


Instruction:
How would you explain what the following Python 3 function does
def mate(self, other):
        "Return a new individual crossing self and other."
        c = random.randrange(len(self.genes))
        return self.__class__(self.genes[:c] + other.genes[c:])

Response: Return a new individual crossing self and other.


Instruction:
Here you have a function in Python 3, explain what it does
def make_undirected(self):
        "Make a digraph into an undirected graph by adding symmetric edges."
        for a in self.dict.keys():
            for (b, distance) in self.dict[a].items():
                self.connect1(b, a, distance)

Response: Make a digraph into an undirected graph by adding symmetric edges.


Instruction:
Given the following Python 3 function, write the documentation
def connect(self, A, B, distance=1):
        self.connect1(A, B, distance)
        if not self.directed: self.connect1(B, A, distance)

Response: Add a link from A and B of given distance.


Instruction:
Make a summary of the following Python 3 code
def connect1(self, A, B, distance):
        "Add a link from A to B of given distance, in one direction only."
        self.dict.setdefault(A,{})[B] = distance

Response: Add a link from A to B of given distance in one direction only.


Instruction:
Can you create a Python 3 function that
returns a link distance or a dict of { node : distance } entries.

Response:
def get(self, a, b=None):
        """Return a link distance or a dict of {node: distance} entries.
        .get(a,b) returns the distance or None;
        .get(a) returns a dict of {node: distance} entries, possibly {}."""
        links = self.dict.setdefault(a, {})
        if b is None: return links
        else: return links.get(b)


Instruction:
Given the following Python 3 function, write the documentation
def actions(self, state):
        "In the leftmost empty column, try all non-conflicting rows."
        if state[-1] is not None:
            return []  # All columns filled; no successors
        else:
            col = state.index(None)
            return [row for row in range(self.N)
                    if not self.conflicted(state, row, col)]

Response: In the leftmost empty column try all non - conflicting rows.


Instruction:
How would you code a function in Python 3 to
place the next queen at the given row.

Response:
def result(self, state, row):
        "Place the next queen at the given row."
        col = state.index(None)
        new = state[:]
        new[col] = row
        return new


Instruction:
Can you generate the documentation for the following Python 3 function
def conflicted(self, state, row, col):
        "Would placing a queen at (row, col) conflict with anything?"
        return any(self.conflict(row, col, state[c], c)
                   for c in range(col))

Response: Would placing a queen at ( row col conflict with anything?


Instruction:
Can you generate the documentation for the following Python 3 function
def conflict(self, row1, col1, row2, col2):
        "Would putting two queens in (row1, col1) and (row2, col2) conflict?"
        return (row1 == row2 ## same row
                or col1 == col2 ## same column
                or row1-col1 == row2-col2  ## same \ diagonal
                or row1+col1 == row2+col2)

Response: Would put two queens in row1 col1 and row2 col2 conflict?


Instruction:
Implement a function in Python 3 to
see if prefix is in dictionary as a full word or as a prefix. Returns two values first is the lowest i such that prefix is in the Wordlist False iff prefix itself is in the Wordlist.

Response:
def lookup(self, prefix, lo=0, hi=None):
        """See if prefix is in dictionary, as a full word or as a prefix.
        Return two values: the first is the lowest i such that
        words[i].startswith(prefix), or is None; the second is
        True iff prefix itself is in the Wordlist."""
        words = self.words
        if hi is None: hi = len(words)
        i = bisect.bisect_left(words, prefix, lo, hi)
        if i < len(words) and words[i].startswith(prefix):
            return i, (words[i] == prefix)
        else:
            return None, False


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_board(self, board=None):
        "Set the board, and find all the words in it."
        if board is None:
            board = random_boggle()
        self.board = board
        self.neighbors = boggle_neighbors(len(board))
        self.found = {}
        for i in range(len(board)):
            lo, hi = self.wordlist.bounds[board[i]]
            self.find(lo, hi, i, [], '')
        return self

Response: Set the board and find all the words in it.


Instruction:
Write a Python 3 function that can
look in square i find the words that continue the prefix and return the i - th entry in visited.

Response:
def find(self, lo, hi, i, visited, prefix):
        """Looking in square i, find the words that continue the prefix,
        considering the entries in self.wordlist.words[lo:hi], and not
        revisiting the squares in visited."""
        if i in visited:
            return
        wordpos, is_word = self.wordlist.lookup(prefix, lo, hi)
        if wordpos is not None:
            if is_word:
                self.found[prefix] = True
            visited.append(i)
            c = self.board[i]
            if c == 'Q': c = 'QU'
            prefix += c
            for j in self.neighbors[i]:
                self.find(wordpos, hi, j, visited, prefix)
            visited.pop()


Instruction:
Given the following Python 3 function, write the documentation
def score(self):
        "The total score for the words found, according to the rules."
        return sum([self.scores[len(w)] for w in self.words()])

Response: The total score for the words found according to the rules.


Instruction:
Given the following Python 3 function, write the documentation
def TraceAgent(agent):
    old_program = agent.program
    def new_program(percept):
        action = old_program(percept)
        print '%s perceives %s and does %s' % (agent, percept, action)
        return action
    agent.program = new_program
    return agent

Response: Wrap the agent s program to print its input and output.


Instruction:
Here you have a function in Python 3, explain what it does
def TableDrivenAgentProgram(table):
    percepts = []
    def program(percept):
        percepts.append(percept)
        action = table.get(tuple(percepts))
        return action
    return program

Response: This agent provides a program that selects an action based on the percept sequence.


Instruction:
Here you have a function in Python 3, explain what it does
def ModelBasedReflexAgentProgram(rules, update_state):
    "This agent takes action based on the percept and state. [Fig. 2.12]"
    def program(percept):
        program.state = update_state(program.state, program.action, percept)
        rule = rule_match(program.state, rules)
        action = rule.action
        return action
    program.state = program.action = None
    return program

Response: This agent takes action based on the percept and state. [ Fig. 2. 12 ]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def ModelBasedVacuumAgent():
    "An agent that keeps track of what locations are clean or dirty."
    model = {loc_A: None, loc_B: None}
    def program((location, status)):
        "Same as ReflexVacuumAgent, except if everything is clean, do NoOp."
        model[location] = status ## Update the model here
        if model[loc_A] == model[loc_B] == 'Clean': return 'NoOp'
        elif status == 'Dirty': return 'Suck'
        elif location == loc_A: return 'Right'
        elif location == loc_B: return 'Left'
    return Agent(program)

Response: An agent that keeps track of what locations are clean or dirty.


Instruction:
Given the following Python 3 function, write the documentation
def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
    envs = [EnvFactory() for i in range(n)]
    return [(A, test_agent(A, steps, copy.deepcopy(envs)))
            for A in AgentFactories]

Response: See how well each of several agents do in n instances of an environment.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def step(self):
        if not self.is_done():
            actions = [agent.program(self.percept(agent))
                       for agent in self.agents]
            for (agent, action) in zip(self.agents, actions):
                self.execute_action(agent, action)
            self.exogenous_change()

Response: Run the environment for one time step.


Instruction:
Make a summary of the following Python 3 code
def run(self, steps=1000):
        "Run the Environment for given number of time steps."
        for step in range(steps):
            if self.is_done(): return
            self.step()

Response: Run the Environment for given number of time steps.


Instruction:
Can you tell what is the following Python 3 function doing
def list_things_at(self, location, tclass=Thing):
        "Return all things exactly at a given location."
        return [thing for thing in self.things
                if thing.location == location and isinstance(thing, tclass)]

Response: Return all things exactly at a given location.


Instruction:
Implement a function in Python 3 to
add a thing to the environment setting its location. For convenience add a thing to the environment setting its performance.

Response:
def add_thing(self, thing, location=None):
        """Add a thing to the environment, setting its location. For
        convenience, if thing is an agent program we make a new agent
        for it. (Shouldn't need to override this."""
        if not isinstance(thing, Thing):
            thing = Agent(thing)
        assert thing not in self.things, "Don't add the same thing twice"
        thing.location = location or self.default_location(thing)
        self.things.append(thing)
        if isinstance(thing, Agent):
            thing.performance = 0
            self.agents.append(thing)


Instruction:
How would you implement a function in Python 3 that
removes a thing from the environment.

Response:
def delete_thing(self, thing):
        """Remove a thing from the environment."""
        try:
            self.things.remove(thing)
        except ValueError, e:
            print e
            print "  in Environment delete_thing"
            print "  Thing to be removed: %s at %s" % (thing, thing.location)
            print "  from list: %s" % [(thing, thing.location)
                                       for thing in self.things]
        if thing in self.agents:
            self.agents.remove(thing)


Instruction:
Make a summary of the following Python 3 code
def things_near(self, location, radius=None):
        "Return all things within radius of location."
        if radius is None: radius = self.perceptible_distance
        radius2 = radius * radius
        return [thing for thing in self.things
                if distance2(location, thing.location) <= radius2]

Response: Return all things within radius of location.


Instruction:
Write a Python 3 script for
moving a thing to a new location.

Response:
def move_to(self, thing, destination):
        "Move a thing to a new location."
        thing.bump = self.some_things_at(destination, Obstacle)
        if not thing.bump:
            thing.location = destination
            for o in self.observers:
                o.thing_moved(thing)


Instruction:
Create a Python 3 function for
putting walls around the entire perimeter of the grid.

Response:
def add_walls(self):
        "Put walls around the entire perimeter of the grid."
        for x in range(self.width):
            self.add_thing(Wall(), (x, 0))
            self.add_thing(Wall(), (x, self.height-1))
        for y in range(self.height):
            self.add_thing(Wall(), (0, y))
            self.add_thing(Wall(), (self.width-1, y))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def percept(self, agent):
        status = if_(self.some_things_at(agent.location, Dirt),
                     'Dirty', 'Clean')
        bump = if_(agent.bump, 'Bump', 'None')
        return (status, bump)

Response: The percept is a tuple of ('Dirty Clean Bump None.


Instruction:
Write a Python 3 function that can
change agent s location and status ; track performance.

Response:
def execute_action(self, agent, action):
        """Change agent's location and/or location's status; track performance.
        Score 10 for each dirt cleaned; -1 for each move."""
        if action == 'Right':
            agent.location = loc_B
            agent.performance -= 1
        elif action == 'Left':
            agent.location = loc_A
            agent.performance -= 1
        elif action == 'Suck':
            if self.status[agent.location] == 'Dirty':
                agent.performance += 10
            self.status[agent.location] = 'Clean'


Instruction:
How would you code a function in Python 3 to
create a dictionary mapping symbols to alternative sequences.

Response:
def Rules(**rules):
    """Create a dictionary mapping symbols to alternative sequences.
    >>> Rules(A = "B C | D E")
    {'A': [['B', 'C'], ['D', 'E']]}
    """
    for (lhs, rhs) in rules.items():
        rules[lhs] = [alt.strip().split() for alt in rhs.split('|')]
    return rules


Instruction:
Explain what the following Python 3 code does
def Lexicon(**rules):
    for (lhs, rhs) in rules.items():
        rules[lhs] = [word.strip() for word in rhs.split('|')]
    return rules

Response: Create a dictionary mapping symbols to alternative words.


Instruction:
Make a summary of the following Python 3 code
def generate_random(grammar=E_, s='S'):
    import random

    def rewrite(tokens, into):
        for token in tokens:
            if token in grammar.rules:
                rewrite(random.choice(grammar.rules[token]), into)
            elif token in grammar.lexicon:
                into.append(random.choice(grammar.lexicon[token]))
            else:
                into.append(token)
        return into

    return ' '.join(rewrite(s.split(), []))

Response: Generate a random entry in a grammar.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def parses(self, words, S='S'):
        if isinstance(words, str):
            words = words.split()
        self.parse(words, S)
        # Return all the parses that span the whole input
        # 'span the whole input' => begin at 0, end at len(words)
        return [[i, j, S, found, []]
                for (i, j, lhs, found, expects) in self.chart[len(words)]
                # assert j == len(words)
                if i == 0 and lhs == S and expects == []]

Response: Return a list of parses ; words can be a list or string.


Instruction:
Here you have a function in Python 3, explain what it does
def parse(self, words, S='S'):
        self.chart = [[] for i in range(len(words)+1)]
        self.add_edge([0, 0, 'S_', [], [S]])
        for i in range(len(words)):
            self.scanner(i, words[i])
        return self.chart

Response:
Parse a list of words ; according to the grammar.
        Leave results in the chart.


Instruction:
Create a Python 3 function to
add edge to chart and see if it extends or predicts another edge.

Response:
def add_edge(self, edge):
        "Add edge to chart, and see if it extends or predicts another edge."
        start, end, lhs, found, expects = edge
        if edge not in self.chart[end]:
            self.chart[end].append(edge)
            if self.trace:
                print '%10s: added %s' % (caller(2), edge)
            if not expects:
                self.extender(edge)
            else:
                self.predictor(edge)


Instruction:
Can you tell what is the following Python 3 function doing
def scanner(self, j, word):
        "For each edge expecting a word of this category here, extend the edge."
        for (i, j, A, alpha, Bb) in self.chart[j]:
            if Bb and self.grammar.isa(word, Bb[0]):
                self.add_edge([i, j+1, A, alpha + [(Bb[0], word)], Bb[1:]])

Response: For each edge expecting a word of this category here extend the edge.


Instruction:
How would you explain what the following Python 3 function does
def predictor(self, (i, j, A, alpha, Bb)):
        "Add to chart any rules for B that could help extend this edge."
        B = Bb[0]
        if B in self.grammar.rules:
            for rhs in self.grammar.rewrites_for(B):
                self.add_edge([j, j, B, [], rhs])

Response: Add to chart any rules for B that could help extend this edge.


Instruction:
Can you generate the documentation for the following Python 3 function
def extender(self, edge):
        "See what edges can be extended by this edge."
        (j, k, B, _, _) = edge
        for (i, j, A, alpha, B1b) in self.chart[j]:
            if B1b and B == B1b[0]:
                self.add_edge([i, k, A, alpha + [edge], B1b[1:]])

Response: See what edges can be extended by this edge.


Instruction:
Can you create a Python 3 function that
adds a SettingDict object to the context as . Automatically creates non - existent settings with an empty value.

Response:
def settings(request):
    """
    Adds a ``SettingDict`` object for the ``Setting`` model to the context as
    ``SETTINGS``. Automatically creates non-existent settings with an empty
    string as the default value.
    """
    settings = Setting.objects.all().as_dict(default='')
    context = {
        'SETTINGS': settings,
    }
    return context


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_child_models(self):
        child_models = []
        # Loop through all models with FKs back to `base_model`.
        for related_object in get_all_related_objects(self.base_model._meta):
            # Django 1.8 deprecated `get_all_related_objects()`. We're still
            # using it for now with the documented work-around for
            # compatibility with Django <=1.7.
            model = getattr(
                related_object, 'related_model', related_object.model)
            # Only consider `base_model` subclasses.
            if issubclass(model, self.base_model):
                class SettingValueAdmin(self.base_admin_class):
                    pass
                child_models.append((model, SettingValueAdmin))
        return child_models

Response: Returns a list of tuples for base_model and base_admin_class subclasses.


Instruction:
Here you have a function in Python 3, explain what it does
def event_values(event, vars):
    if isinstance(event, tuple) and len(event) == len(vars):
        return event
    else:
        return tuple([event[var] for var in vars])

Response: Return a tuple of the values of variables vars in event.


Instruction:
Create a Python 3 function to
return a probability distribution over the values of the variable X given the observations e in the JointProbDist P.

Response:
def enumerate_joint_ask(X, e, P):
    """Return a probability distribution over the values of the variable X,
    given the {var:val} observations e, in the JointProbDist P. [Section 13.3]
    >>> P = JointProbDist(['X', 'Y'])
    >>> P[0,0] = 0.25; P[0,1] = 0.5; P[1,1] = P[2,1] = 0.125
    >>> enumerate_joint_ask('X', dict(Y=1), P).show_approx()
    '0: 0.667, 1: 0.167, 2: 0.167'
    """
    assert X not in e, "Query variable must be distinct from evidence"
    Q = ProbDist(X) # probability distribution for X, initially empty
    Y = [v for v in P.variables if v != X and v not in e] # hidden vars.
    for xi in P.values(X):
        Q[xi] = enumerate_joint(Y, extend(e, X, xi), P)
    return Q.normalize()


Instruction:
Can you generate the documentation for the following Python 3 function
def enumerate_joint(vars, e, P):
    if not vars:
        return P[e]
    Y, rest = vars[0], vars[1:]
    return sum([enumerate_joint(rest, extend(e, Y, y), P)
                for y in P.values(Y)])

Response: Return the sum of those entries in P consistent with e.


Instruction:
Make a summary of the following Python 3 code
def enumeration_ask(X, e, bn):
    assert X not in e, "Query variable must be distinct from evidence"
    Q = ProbDist(X)
    for xi in bn.variable_values(X):
        Q[xi] = enumerate_all(bn.vars, extend(e, X, xi), bn)
    return Q.normalize()

Response: Return the conditional probability distribution of variable X given evidence e from BayesNet bn.


Instruction:
Write a Python 3 function for
returning the sum of those entries in P consistent with e where P is the joint distribution represented by bn.

Response:
def enumerate_all(vars, e, bn):
    """Return the sum of those entries in P(vars | e{others})
    consistent with e, where P is the joint distribution represented
    by bn, and e{others} means e restricted to bn's other variables
    (the ones other than vars). Parents must precede children in vars."""
    if not vars:
        return 1.0
    Y, rest = vars[0], vars[1:]
    Ynode = bn.variable_node(Y)
    if Y in e:
        return Ynode.p(e[Y], e) * enumerate_all(rest, e, bn)
    else:
        return sum(Ynode.p(y, e) * enumerate_all(rest, extend(e, Y, y), bn)
                   for y in bn.variable_values(Y))


Instruction:
How would you explain what the following Python 3 function does
def elimination_ask(X, e, bn):
    assert X not in e, "Query variable must be distinct from evidence"
    factors = []
    for var in reversed(bn.vars):
        factors.append(make_factor(var, e, bn))
        if is_hidden(var, X, e):
            factors = sum_out(var, factors, bn)
    return pointwise_product(factors, bn).normalize()

Response: Compute bn s P by variable elimination.


Instruction:
How would you code a function in Python 3 to
return the factor for var in bn s joint distribution given e. That is the factor for var in bn s full joint distribution given e. is the pointwise product of these factors for bn s variables.

Response:
def make_factor(var, e, bn):
    """Return the factor for var in bn's joint distribution given e.
    That is, bn's full joint distribution, projected to accord with e,
    is the pointwise product of these factors for bn's variables."""
    node = bn.variable_node(var)
    vars = [X for X in [var] + node.parents if X not in e]
    cpt = dict((event_values(e1, vars), node.p(e1[var], e1))
               for e1 in all_events(vars, bn, e))
    return Factor(vars, cpt)


Instruction:
Can you write a function in Python 3 where it
eliminates var from all factors by summing over its values.

Response:
def sum_out(var, factors, bn):
    "Eliminate var from all factors by summing over its values."
    result, var_factors = [], []
    for f in factors:
        (var_factors if var in f.vars else result).append(f)
    result.append(pointwise_product(var_factors, bn).sum_out(var, bn))
    return result


Instruction:
Can you write a function in Python 3 where it
yields every way of extending e with values for all vars.

Response:
def all_events(vars, bn, e):
    "Yield every way of extending e with values for all vars."
    if not vars:
        yield e
    else:
        X, rest = vars[0], vars[1:]
        for e1 in all_events(rest, bn, e):
            for x in bn.variable_values(X):
                yield extend(e1, X, x)


Instruction:
How would you explain what the following Python 3 function does
def prior_sample(bn):
    event = {}
    for node in bn.nodes:
        event[node.variable] = node.sample(event)
    return event

Response: Randomly sample from bn s full joint distribution.


Instruction:
Explain what the following Python 3 code does
def rejection_sampling(X, e, bn, N):
    counts = dict((x, 0) for x in bn.variable_values(X)) # bold N in Fig. 14.14
    for j in xrange(N):
        sample = prior_sample(bn) # boldface x in Fig. 14.14
        if consistent_with(sample, e):
            counts[sample[X]] += 1
    return ProbDist(X, counts)

Response: Estimate the probability distribution of variable X given an evidence e in BayesNet bn using N samples.


Instruction:
Implement a function in Python 3 to
am event consistent with the given evidence?

Response:
def consistent_with(event, evidence):
    "Is event consistent with the given evidence?"
    return every(lambda (k, v): evidence.get(k, v) == v,
                 event.items())


Instruction:
Can you tell what is the following Python 3 function doing
def likelihood_weighting(X, e, bn, N):
    W = dict((x, 0) for x in bn.variable_values(X))
    for j in xrange(N):
        sample, weight = weighted_sample(bn, e) # boldface x, w in Fig. 14.15
        W[sample[X]] += weight
    return ProbDist(X, W)

Response:
Estimate the probability distribution of variable X given
    evidence e in BayesNet bn.


Instruction:
Create a Python 3 function for
sampling an event from bn that s consistent with the evidence e ; return the event and its weight the likelihood that the event accords to the evidence e.

Response:
def weighted_sample(bn, e):
    """Sample an event from bn that's consistent with the evidence e;
    return the event and its weight, the likelihood that the event
    accords to the evidence."""
    w = 1
    event = dict(e) # boldface x in Fig. 14.15
    for node in bn.nodes:
        Xi = node.variable
        if Xi in e:
            w *= node.p(e[Xi], event)
        else:
            event[Xi] = node.sample(event)
    return event, w


Instruction:
How would you code a function in Python 3 to
return a sample from P where mb denotes that the variables in the Markov blanket of X take their values from event e. The Markov blanket of X is X and e are assigned a value to each. The Markov blanket of X is X and e are assigned a value to each. The Markov blanket of X is the same as the Markov blanket of X.

Response:
def markov_blanket_sample(X, e, bn):
    """Return a sample from P(X | mb) where mb denotes that the
    variables in the Markov blanket of X take their values from event
    e (which must assign a value to each). The Markov blanket of X is
    X's parents, children, and children's parents."""
    Xnode = bn.variable_node(X)
    Q = ProbDist(X)
    for xi in bn.variable_values(X):
        ei = extend(e, X, xi)
        # [Equation 14.12:]
        Q[xi] = Xnode.p(xi, e) * product(Yj.p(ei[Yj.variable], ei)
                                         for Yj in Xnode.children)
    return probability(Q.normalize()[True])


Instruction:
Can you generate the documentation for the following Python 3 function
def normalize(self):
        total = float(sum(self.prob.values()))
        if not (1.0-epsilon < total < 1.0+epsilon):
            for val in self.prob:
                self.prob[val] /= total
        return self

Response: Make sure the probabilities of all values sum to 1. Returns the normalized distribution.


Instruction:
Implement a function in Python 3 to
show the probabilities rounded and sorted by key for the sake of portable doctests.

Response:
def show_approx(self, numfmt='%.3g'):
        """Show the probabilities rounded and sorted by key, for the
        sake of portable doctests."""
        return ', '.join([('%s: ' + numfmt) % (v, p)
                          for (v, p) in sorted(self.prob.items())])


Instruction:
Here you have a function in Python 3, explain what it does
def add(self, node_spec):
        node = BayesNode(*node_spec)
        assert node.variable not in self.vars
        assert every(lambda parent: parent in self.vars, node.parents)
        self.nodes.append(node)
        self.vars.append(node.variable)
        for parent in node.parents:
            self.variable_node(parent).children.append(node)

Response: Add a node to the net.


Instruction:
Create a Python 3 function for
returning the node for the variable named var.

Response:
def variable_node(self, var):
        """Return the node for the variable named var.
        >>> burglary.variable_node('Burglary').variable
        'Burglary'"""
        for n in self.nodes:
            if n.variable == var:
                return n
        raise Exception("No such variable: %s" % var)


Instruction:
Can you implement a function in Python 3 that
returns the conditional probability of the logarithmic probability of the event.

Response:
def p(self, value, event):
        """Return the conditional probability
        P(X=value | parents=parent_values), where parent_values
        are the values of parents in event. (event must assign each
        parent a value.)
        >>> bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625})
        >>> bn.p(False, {'Burglary': False, 'Earthquake': True})
        0.375"""
        assert isinstance(value, bool)
        ptrue = self.cpt[event_values(event, self.parents)]
        return if_(value, ptrue, 1 - ptrue)


Instruction:
How would you explain what the following Python 3 function does
def pointwise_product(self, other, bn):
        "Multiply two factors, combining their variables."
        vars = list(set(self.vars) | set(other.vars))
        cpt = dict((event_values(e, vars), self.p(e) * other.p(e))
                   for e in all_events(vars, bn, {}))
        return Factor(vars, cpt)

Response: Multiply two factors combining their variables.


Instruction:
Can you write a function in Python 3 where it
makes a factor eliminating var by summing over its values.

Response:
def sum_out(self, var, bn):
        "Make a factor eliminating var by summing over its values."
        vars = [X for X in self.vars if X != var]
        cpt = dict((event_values(e, vars),
                    sum(self.p(extend(e, var, val))
                        for val in bn.variable_values(var)))
                   for e in all_events(vars, bn, {}))
        return Factor(vars, cpt)


Instruction:
Can you generate the documentation for the following Python 3 function
def normalize(self):
        "Return my probabilities; must be down to one variable."
        assert len(self.vars) == 1
        return ProbDist(self.vars[0],
                        dict((k, v) for ((k,), v) in self.cpt.items()))

Response: Return my probabilities ; must be down to one variable.


Instruction:
Can you tell what is the following Python 3 function doing
def next_chunk_boundaries(self, buf, prepend_bytes=0):
        return (boundary for boundary, _ in self.next_chunk_boundaries_levels(buf, prepend_bytes))

Response: Computes the next chunk boundaries within buf.


Instruction:
Can you write a function in Python 3 where it
computes the next chunk boundaries within buf.

Response:
def next_chunk_boundaries_levels(self, buf, prepend_bytes=0):
        """Computes the next chunk boundaries within `buf`.

        Similar to :meth:`.next_chunk_boundaries`, but information about which chunker led to a respective boundary is
        included in the returned value.

        Args:
            buf (bytes): The message that is to be chunked.
            prepend_bytes (Optional[int]): Optional number of zero bytes that should be input to the chunking algorithm
                before `buf`.

        Returns:
            list: List of tuples (boundary, level), where boundary is a boundary position relative to `buf` and level is
                the index of the chunker (i.e., the index of its chunk size specified during instantiation) that yielded
                the boundary.

            If multiple chunkers yield the same boundary, it is returned only once, along with the highest matching
            chunker index.
        """
        boundaries = {}
        for level_index, chunker in enumerate(self._chunkers):
            boundaries.update(
                dict([(boundary, level_index) for boundary in chunker.next_chunk_boundaries(buf, prepend_bytes)]))
        return sorted(boundaries.items())


Instruction:
Create a Python 3 function to
create a chunker performing content - defined chunking using Rabin Karp s rolling hash scheme with the specified chunk size.

Response:
def create_chunker(self, chunk_size):
        """Create a chunker performing content-defined chunking (CDC) using Rabin Karp's rolling hash scheme with a
        specific, expected chunk size.

        Args:
            chunk_size (int): (Expected) target chunk size.

        Returns:
            BaseChunker: A chunker object.
        """
        rolling_hash = _rabinkarprh.RabinKarpHash(self.window_size, self._seed)
        rolling_hash.set_threshold(1.0 / chunk_size)
        return RabinKarpCDC._Chunker(rolling_hash)


Instruction:
Write a Python 3 script for
creating a multi - level chunker performing content - defined chunking using Rabin Karp s rolling hash scheme.

Response:
def create_multilevel_chunker(self, chunk_sizes):
        """Create a multi-level chunker performing content-defined chunking (CDC) using Rabin Karp's rolling hash scheme
        with different specific, expected chunk sizes.

        Args:
            chunk_sizes (list): List of (expected) target chunk sizes.

                Warning:
                    For performance reasons, behavior is only defined if chunk sizes are passed in order, i.e., from
                    lowest to highest value.

        Returns:
            BaseMultiLevelChunker: A multi-level chunker object.
        """
        rolling_hash = _rabinkarprh.RabinKarpMultiThresholdHash(self.window_size, self._seed,
                                                                [1.0 / chunk_size for chunk_size in chunk_sizes])
        return RabinKarpCDC._MultiLevelChunker(rolling_hash)


Instruction:
Given the following Python 3 function, write the documentation
def brightness(level=100, group=0):
    if level not in range(0,101):
        raise Exception("Brightness must be value between 0 and 100")
    b = int(floor(level / 4.0) + 2) #lights want values 2-27
    return (COMMANDS['ON'][group], Command(0x4E, b))

Response: Returns a command that sets the brightness of the given level.


Instruction:
Create a Python 3 function for
stripping all whitespace from a minidom XML node and its children Arcs.

Response:
def strip_minidom_whitespace(node):
    """Strips all whitespace from a minidom XML node and its children

    This operation is made in-place."""
    for child in node.childNodes:
        if child.nodeType == Node.TEXT_NODE:
            if child.nodeValue:
                child.nodeValue = child.nodeValue.strip()
        elif child.nodeType == Node.ELEMENT_NODE:
            strip_minidom_whitespace(child)


Instruction:
Can you implement a function in Python 3 that
returns a tuple of commands that can be used to set the brightness of a single light.

Response:
def brightness(level=100, group=0):
    """ Assumes level is out of 100 """
    if level not in range(0,101):
        raise Exception("Brightness must be value between 0 and 100")
    b = int(floor(level / 10.0)) #lights have 10 levels of brightness
    commands = list(darkest(group))
    for i in range(0, b):
        commands.append(COMMANDS['BRIGHTER'])
    return tuple(commands)


Instruction:
Make a summary of the following Python 3 code
def warmness(level=100, group=0):
    if level not in range(0,101):
        raise Exception("Warmness must be value between 0 and 100")
    b = int(floor(level / 10.0)) #lights have 10 levels of warmness
    commands = list(coolest(group))
    for i in range(0, b):
        commands.append(COMMANDS['WARMER'])
    return tuple(commands)

Response: Returns a tuple of warmness commands.