Skip to main content

Command Palette

Search for a command to run...

AI Prac

AI

Updated
•27 min read•View as Markdown
*Practical 1*
AIM:
a. Implement Breadth first search algorithm for Romanian map problem.

CODE:
from collections import deque

infinty = float('inf')

class Node:
    def __init__(self, state, parent=None, action=None, path_cost=0):
        self.state= state
        self.parent = parent
        self.action = action
        self.path_cost = path_cost
        self.depth = 0
        if parent:
            self.depth = parent.depth + 1

    def path(self): 
        node, path_back = self,[]
        while node:
            path_back.append(node)
            node = node.parent
        return list(reversed(path_back))  

    def __repr__(self):      
        return "<Node {}>".format(self.state)

    def expand(self, problem): 
        return [self.child_node(problem, action) for action in problem.actions(self.state)]

    def child_node(self, problem, action): 
        next_state = problem.result(self.state, action)
        next_node = Node(next_state, self, action, problem.path_cost(self.path_cost, self.state, action, next_state))
        return next_node

    def solution(self): 
        return [node.state for node in self.path()]

class Problem(object): 
    def __init__(self, initial, goal=None):
        self.initial = initial
        self.goal = goal

    def actions(self, state):
        raise NotImplementedError

    def result(self, state, action):
        raise NotImplementedError

    def goal_test(self, state):
        return state == self.goal

    def path_cost(self, c, state1, action, state2):
        return c+1

    def value(self, state):
        raise NotImplementedError

class GraphProblem(Problem):
    def __init__(self, initial, goal, graph):
        Problem.__init__(self, initial, goal)
        self.graph = graph

    def actions(self, A):
        return list(self.graph.get(A).keys())

    def result(self, state, action):
        return action

    def path_cost(self, cost_so_far, A, action, B):
        return cost_so_far + (self.graph.get(A, B) or infinity)

class Graph:
    def __init__(self, graph_dict=None, directed=True):
        self.graph_dict = graph_dict or ()
        self.directed = directed
        if not directed:
            self.make_undirected()
    def make_undirected (self):
        for a in list (self.graph_dict.keys()):
            print("processing node", a)
            for (b, dist) in self.graph_dict[a].items():
                print("-->", a, " connects ", b," by distance :", dist)

    def get(self, a, b=None):
        links = self.graph_dict.get(a)
        if b is None:
            return links
        else:
            cost = links.get(b)
            return cost

def UndirectedGraph(graph_dict=None):
    return Graph(graph_dict=graph_dict, directed=False)

def breadth_first_tree_search(problem):
    frontier = deque([Node(problem.initial)])
    print("Search begins from :",frontier)
    while frontier:
        node = frontier.popleft()
        print("Now Exploring...",node)
        if problem.goal_test(node.state):
            return node
        x = node.expand(problem)
        print("Expanded Nodes :",x)
        frontier.extend(x)
    return None

romania_map = UndirectedGraph({
    'Arad': {'Sibiu':140, 'Zerind':75, 'Timisoara':118},
    'Zerind':{'Arad':75, 'Oradea':71},
    'Oradea': {'Zerind':71, 'Sibiu':151},
    'Sibiu': {'Arad':140, 'Oradea':151, 'Fagaras':99, 'Rimnicu':80},
    'Timisoara': {'Arad':118, 'Lugoj':111},
    'Lugoj': {'Timisoara':111, 'Mehadia':70},
    'Mehadia': {'Lugoj':70, 'Drobeta':75},
    'Drobeta': {'Mehadia':75, 'Craiova':120},
    'Craiova': {'Drobeta':120, 'Rimnicu':146, 'Pitesti':138},
    'Rimnicu': {'Sibiu':80, 'Craiova':146, 'Pitesti':97},
    'Fagaras': {'Sibiu':99, 'Bucharest':211},
    'Pitesti': {'Rimnicu':97, 'Craiova':138, 'Bucharest':101},
    'Bucharest': {'Fagaras':211, 'Pitesti':101, 'Giurgiu':90, 'Urziceni':85},
    'Giurgiu': {'Bucharest':90},
    'Urziceni': {'Bucharest':85, 'Vaslui':142, 'Hirsova':98},
    'Hirsova': {'Urziceni':98, 'Eforie':86},
    'Eforie': {'Hirsova':86},
    'Vaslui': {'Iasi':92, 'Urziceni':142},
    'Iasi': {'Vaslui':92, 'Neamt':87},
    'Neamt': {'Iasi':87}
})

romania_problem = GraphProblem('Arad' , 'Bucharest', romania_map)

print("Keys of Arad", romania_problem.actions('Arad'))

finalnode = breadth_first_tree_search(romania_problem)

print("solution of ", romania_problem.initial, "to", romania_problem.goal,finalnode.solution())
print("path cost of final node  = ", finalnode.path_cost)

(b). Implement Breadth first search algorithm for Mumbai-Pune-Belgaum-Goa-map problem.

CODE: 
from collections import deque 
infinity = float('inf') 
class Node: 
def __init__(self, state, parent=None,action=None, path_cost=0): 
self.state = state 
self.parent = parent 
self.action = action 
self.path_cost = path_cost 
self.depth = 0 
if parent: 
self.depth = parent.depth + 1 
def path(self): 
node , path_back = self, [] 
while node: 
path_back.append(node) 
node = node.parent 
return list(reversed(path_back)) 
def __repr__(self) -> str: 
return "<Node {}>".format(self.state) 
def expand(self, problem): 
return (self.child_node(problem, action) for action in problem.actions(self.state)) 
def child_node(self, problem, action): 
next_state = problem.result(self.state, action) 
 next_node = Node(next_state, self,action, problem.path_cost(self.path_cost, self.state, 
action, next_state)) 
        return next_node 

    def solution(self): 
        return [node.state for node in self.path()] 

class problem(object): 
    def __init__(self, initial, goal=None): 
        self.initial = initial 
        self.goal = goal 

    def actions(self, state): 
        raise NotImplementedError 

    def result(self , state , action): 
        raise NotImplementedError 

    def goal_test(self , state): 
        return state == self.goal 

    def path_cost(self,c ,state1, action,state2): 
        return c+1 

    def value(self, state): 
        raise NotImplementedError 

class GraphProblem(problem): 
    def __init__(self, initial, goal, graph): 
        problem.__init__(self, initial, goal) 
        self.graph = graph 

    def actions(self, A): 
        return self.graph.get(A) 

    def result(self,state,action): 
        return action 


def breadth_first_item_search(problem): 
    frontier = deque([Node(problem.initial)]) 
    print(f"Search begins from: {frontier}") 
    while frontier: 
        node = frontier.popleft() 

        if problem.goal_test(node.state): 
            return node 

        x = node.expand(problem)  
frontier.extend(x) 
return None 
belgaumtogoa_map ={ 
'Belgaum':['Peerwadi Cross','Khanpur','Sankeshwar'], 
'Peerwadi Cross':['Belgaum','Jamboti','Khanpur'], 
'Khanpur':['Peerwadi Cross','Anmod'], 
'Jamboti':['Peerwadi Cross','Chorla'], 
'Anmod':['Ponda','Khanpur'], 
'Chorla':['Mapusa','Jamboti'], 
'Ponda':['Panjim','Margao','Anmod'], 
'Margao':['Panjim','Ponda'], 
'Panjim':['Ponda','Margao','Mapusa'], 
'Mapusa':['Sawantwadi','Panjim','Chorla'], 
'Sawantwadi':['Amboli','Mapusa'], 
'Amboli':['Sawantwadi','Ajara'], 
'Ajara':['Amboli','Sankeshwar','Nipani'], 
'Sankeshwar':['Nipani','Ajara','Belgaum'], 
'Nipani':['Sankeshwar','Ajara']  
} 
source_state = input("Enter the Source State: ") 
dest_state = input("Enter the destination state: ") 
belgaumtogoamap_problem = GraphProblem(source_state, dest_state, belgaumtogoa_map) 
print(f"Keys of {source_state}: ", belgaumtogoamap_problem.actions(source_state)) 
finalnode = breadth_first_item_search(belgaumtogoamap_problem) 
print("Solution of ", belgaumtogoamap_problem.initial, " to ", 
belgaumtogoamap_problem.goal, finalnode.solution()) 

****************************Practical 2*************************************
Aim: Implement Iterative deep depth first search for Romanian map problem.

CODE:
from collections import deque
import sys
infinty = float('inf')

class Node:
    def __init__(self, state, parent=None, action=None, path_cost=0):
        self.state= state
        self.parent = parent
        self.action = action
        self.path_cost = path_cost
        self.depth = 0
        if parent:
            self.depth = parent.depth + 1

    def __repr__(self):      
        return "<Node {}>".format(self.state)

    def expand(self, problem): 
        return [self.child_node(problem, action)
                for action in problem.actions(self.state)]

    def child_node(self, problem, action): 
        next_state = problem.result(self.state, action)
        next_node = Node(next_state, self, action,
                         problem.path_cost(self.path_cost, self.state,
                                           action, next_state))
        return next_node

    def solution(self): 
        return [node.state for node in self.path()[1:]]

    def path(self): 
        node, path_back = self,[]
        while node:
            path_back.append(node)
            node = node.parent
        return list(reversed(path_back))  

class Problem(object): 
    def __init__(self, initial, goal=None):
        self.initial = initial
        self.goal = goal

    def actions(self, state):
        raise NotImplementedError

    def result(self, state, action):
        raise NotImplementedError

    def goal_test(self, state):
        if isinstance(self.goal, list):
            return is_in(state, self.goal)
        else:
            return state == self.goal

    def path_cost(self, c, state1, action, state2):
        return c + 1

class GraphProblem(Problem): 
    def __init__(self, initial, goal, graph):
        Problem.__init__(self, initial, goal)
        self.graph = graph

    def actions(self, A):
        return list(self.graph.get(A).keys())

    def result(self, state, action):
        return action

    def path_cost(self, cost_so_far, A, action, B):
        return cost_so_far + (self.graph.get(A, B) or infinity)

class Graph:
    def __init__(self, graph_dict=None, directed=True):
        self.graph_dict = graph_dict or {}
        self.directed = directed
        if not directed:
            self.make_undirected()

    def make_undirected (self):
        for a in list (self.graph_dict.keys()):
            for (b, dist) in self.graph_dict[a].items():           
                self.connect1(b, a, dist)

    def connect1(self, A, B, distance):
        self.graph_dict.setdefault(A, {})[B] = distance

    def get(self, a, b=None):
        links = self.graph_dict.setdefault(a, {})
        if b is None:
            return links
        else:
            return links.get(b)

def UndirectedGraph(graph_dict=None): 
    return Graph(graph_dict=graph_dict, directed=False)

def iterative_deepening_search(problem, limit):
    for depth in range(0, limit):
        print("Checking with depth:", depth)
        result = depth_limited_search(problem, depth)
        print("Result: ", result)
    return result

def depth_limited_search(problem, limit=50):
    def recursive_dls(node, problem, limit):
        if problem.goal_test(node.state):
            return node
        elif limit == 0:
            return 'cutoff'
        else:
            cutoff_occurred = False
            for child in node.expand(problem):
                result = recursive_dls(child, problem, limit - 1)
                if result == 'cutoff':
                    cutoff_occurred = True
                elif result is not None:
                    return result
            return 'cutoff' if cutoff_occurred else 'Not found'
    return recursive_dls(Node(problem.initial), problem, limit)


romania_map = UndirectedGraph({
    'Arad': {'Sibiu':140, 'Zerind':75, 'Timisoara':118},
    'Zerind':{'Arad':75, 'Oradea':71},
    'Oradea': {'Zerind':71, 'Sibiu':151},
    'Sibiu': {'Arad':140, 'Oradea':151, 'Fagaras':99, 'Rimnicu':80},
    'Timisoara': {'Arad':118, 'Lugoj':111},
    'Lugoj': {'Timisoara':111, 'Mehadia':70},
    'Mehadia': {'Lugoj':70, 'Drobeta':75},
    'Drobeta': {'Mehadia':75, 'Craiova':120},
    'Craiova': {'Drobeta':120, 'Rimnicu':146, 'Pitesti':138},
    'Rimnicu': {'Sibiu':80, 'Craiova':146, 'Pitesti':97},
    'Fagaras': {'Sibiu':99, 'Bucharest':211},
    'Pitesti': {'Rimnicu':97, 'Craiova':138, 'Bucharest':101},
    'Bucharest': {'Fagaras':211, 'Pitesti':101, 'Giurgiu':90, 'Urziceni':85},
    'Giurgiu': {'Bucharest':90},
    'Urziceni': {'Bucharest':85, 'Vaslui':142, 'Hirsova':98},
    'Hirsova': {'Urziceni':98, 'Eforie':86},
    'Eforie': {'Hirsova':86},
    'Vaslui': {'Iasi':92, 'Urziceni':142},
    'Iasi': {'Vaslui':92, 'Neamt':87},
    'Neamt': {'Iasi':87}
})

print("searching from arad to bucharest with level 5...")
romania_problem = GraphProblem('Arad' , 'Bucharest', romania_map)
print(iterative_deepening_search(romania_problem, 5))

print("searching from arad to sibiu with level 2...")
romania_problem = GraphProblem('Arad' , 'Sibiu', romania_map)
print(iterative_deepening_search(romania_problem, 2))

******************************Practical 3********************************
Aim: Implement A* search algorithm for Romanian map problem.

*********************************myutils.py************************************
"""Provides some utilities widely used by other modules"""

import bisect
import collections
import collections.abc
import heapq
import operator
import os.path
import random
import math
import functools
from itertools import chain, combinations

# ______________________________________________________________________________
# Functions on Sequences and Iterables

def sequence(iterable):
    """Coerce iterable to sequence, if it is not already one."""
    return (iterable if isinstance(iterable, collections.abc.Sequence)
            else tuple(iterable))

def removeall(item, seq):
    """Return a copy of seq (or string) with all occurrences of item removed."""
    if isinstance(seq, str):
        return seq.replace(item, '')
    else:
        return [x for x in seq if x != item]

def unique(seq):  # TODO: replace with set
    """Remove duplicate elements from seq. Assumes hashable elements."""
    return list(set(seq))

def count(seq):
    """Count the number of items in sequence that are interpreted as true."""
    return sum(bool(x) for x in seq)

def product(numbers):
    """Return the product of the numbers, e.g. product([2, 3, 10]) == 60"""
    result = 1
    for x in numbers:
        result *= x
    return result

def first(iterable, default=None):
    """Return the first element of an iterable or the next element of a generator; or default."""
    try:
        return iterable[0]
    except IndexError:
        return default
    except TypeError:
        return next(iterable, default)

def is_in(elt, seq):
    """Similar to (elt in seq), but compares with 'is', not '=='."""
    return any(x is elt for x in seq)

def mode(data):
    """Return the most common data item. If there are ties, return any one of them."""
    [(item, count)] = collections.Counter(data).most_common(1)
    return item

def powerset(iterable):
    """powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"""
    s = list(iterable)
    return list(chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)))[1:]

# ______________________________________________________________________________
# argmin and argmax

identity = lambda x: x

argmin = min
argmax = max

def argmin_random_tie(seq, key=identity):
    """Return a minimum element of seq; break ties at random."""
    return argmin(shuffled(seq), key=key)

def argmax_random_tie(seq, key=identity):
    """Return an element with highest fn(seq[i]) score; break ties at random."""
    return argmax(shuffled(seq), key=key)

def shuffled(iterable):
    """Randomly shuffle a copy of iterable."""
    items = list(iterable)
    random.shuffle(items)
    return items

# ______________________________________________________________________________
# Statistical and mathematical functions

def histogram(values, mode=0, bin_function=None):
    """Return a list of (value, count) pairs, summarizing the input values.
    Sorted by increasing value, or if mode=1, by decreasing count.
    If bin_function is given, map it over values first."""
    if bin_function:
        values = map(bin_function, values)

    bins = {}
    for val in values:
        bins[val] = bins.get(val, 0) + 1

    if mode:
        return sorted(list(bins.items()), key=lambda x: (x[1], x[0]),
                      reverse=True)
    else:
        return sorted(bins.items())

def dotproduct(X, Y):
    """Return the sum of the element-wise product of vectors X and Y."""
    return sum(x * y for x, y in zip(X, Y))

def element_wise_product(X, Y):
    """Return vector as an element-wise product of vectors X and Y"""
    assert len(X) == len(Y)
    return [x * y for x, y in zip(X, Y)]

def matrix_multiplication(X_M, *Y_M):
    """Return a matrix as a matrix-multiplication of X_M and arbitrary number of matrices *Y_M"""

    def _mat_mult(X_M, Y_M):
        """Return a matrix as a matrix-multiplication of two matrices X_M and Y_M
        >>> matrix_multiplication([[1, 2, 3],
                                   [2, 3, 4]],
                                   [[3, 4],
                                    [1, 2],
                                    [1, 0]])
        [[8, 8],[13, 14]]
        """
        assert len(X_M[0]) == len(Y_M)

        result = [[0 for i in range(len(Y_M[0]))] for j in range(len(X_M))]
        for i in range(len(X_M)):
            for j in range(len(Y_M[0])):
                for k in range(len(Y_M)):
                    result[i][j] += X_M[i][k] * Y_M[k][j]
        return result

    result = X_M
    for Y in Y_M:
        result = _mat_mult(result, Y)

    return result

def vector_to_diagonal(v):
    """Converts a vector to a diagonal matrix with vector elements
    as the diagonal elements of the matrix"""
    diag_matrix = [[0 for i in range(len(v))] for j in range(len(v))]
    for i in range(len(v)):
        diag_matrix[i][i] = v[i]

    return diag_matrix

def vector_add(a, b):
    """Component-wise addition of two vectors."""
    return tuple(map(operator.add, a, b))

def scalar_vector_product(X, Y):
    """Return vector as a product of a scalar and a vector"""
    return [X * y for y in Y]

def scalar_matrix_product(X, Y):
    """Return matrix as a product of a scalar and a matrix"""
    return [scalar_vector_product(X, y) for y in Y]

def inverse_matrix(X):
    """Inverse a given square matrix of size 2x2"""
    assert len(X) == 2
    assert len(X[0]) == 2
    det = X[0][0] * X[1][1] - X[0][1] * X[1][0]
    assert det != 0
    inv_mat = scalar_matrix_product(1.0 / det, [[X[1][1], -X[0][1]], [-X[1][0], X[0][0]]])

    return inv_mat

def probability(p):
    """Return true with probability p."""
    return p > random.uniform(0.0, 1.0)

def weighted_sample_with_replacement(n, seq, weights):
    """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 _ in range(n)]

def weighted_sampler(seq, weights):
    """Return a random-sample function that picks from seq weighted by weights."""
    totals = []
    for w in weights:
        totals.append(w + totals[-1] if totals else w)

    return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]

def rounder(numbers, d=4):
    """Round a single number, or sequence of numbers, to d decimal places."""
    if isinstance(numbers, (int, float)):
        return round(numbers, d)
    else:
        constructor = type(numbers)  # Can be list, set, tuple, etc.
        return constructor(rounder(n, d) for n in numbers)

def num_or_str(x):
    """The argument is a string; convert to a number if
       possible, or strip it."""
    try:
        return int(x)
    except ValueError:
        try:
            return float(x)
        except ValueError:
            return str(x).strip()

def normalize(dist):
    """Multiply each number by a constant such that the sum is 1.0"""
    if isinstance(dist, dict):
        total = sum(dist.values())
        for key in dist:
            dist[key] = dist[key] / total
            assert 0 <= dist[key] <= 1, "Probabilities must be between 0 and 1."
        return dist
    total = sum(dist)
    return [(n / total) for n in dist]

def norm(X, n=2):
    """Return the n-norm of vector X"""
    return sum([x ** n for x in X]) ** (1 / n)

def clip(x, lowest, highest):
    """Return x clipped to the range [lowest..highest]."""
    return max(lowest, min(x, highest))

def sigmoid_derivative(value):
    return value * (1 - value)

def sigmoid(x):
    """Return activation value of x with sigmoid function"""
    return 1 / (1 + math.exp(-x))

def step(x):
    """Return activation value of x with sign function"""
    return 1 if x >= 0 else 0

def gaussian(mean, st_dev, x):
    """Given the mean and standard deviation of a distribution, it returns the probability of x."""
    return 1 / (math.sqrt(2 * math.pi) * st_dev) * math.e ** (-0.5 * (float(x - mean) / st_dev) ** 2)

try:  # math.isclose was added in Python 3.5; but we might be in 3.4
    from math import isclose
except ImportError:
    def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
        """Return true if numbers a and b are close to each other."""
        return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

def weighted_choice(choices):
    """A weighted version of random.choice"""
    # NOTE: Shoule be replaced by random.choices if we port to Python 3.6

    total = sum(w for _, w in choices)
    r = random.uniform(0, total)
    upto = 0
    for c, w in choices:
        if upto + w >= r:
            return c, w
        upto += w

# ______________________________________________________________________________
# Grid Functions

orientations = EAST, NORTH, WEST, SOUTH = [(1, 0), (0, 1), (-1, 0), (0, -1)]
turns = LEFT, RIGHT = (+1, -1)

def turn_heading(heading, inc, headings=orientations):
    return headings[(headings.index(heading) + inc) % len(headings)]

def turn_right(heading):
    return turn_heading(heading, RIGHT)

def turn_left(heading):
    return turn_heading(heading, LEFT)

def distance(a, b):
    """The distance between two (x, y) points."""
    xA, yA = a
    xB, yB = b
    return math.hypot((xA - xB), (yA - yB))

def distance_squared(a, b):
    """The square of the distance between two (x, y) points."""
    xA, yA = a
    xB, yB = b
    return (xA - xB) ** 2 + (yA - yB) ** 2

def vector_clip(vector, lowest, highest):
    """Return vector, except if any element is less than the corresponding
    value of lowest or more than the corresponding value of highest, clip to
    those values."""
    return type(vector)(map(clip, vector, lowest, highest))

# ______________________________________________________________________________
# Misc Functions

class injection():
    """Dependency injection of temporary values for global functions/classes/etc.
    E.g., `with injection(DataBase=MockDataBase): ...`"""

    def __init__(self, **kwds):
        self.new = kwds

    def __enter__(self):
        self.old = {v: globals()[v] for v in self.new}
        globals().update(self.new)

    def __exit__(self, type, value, traceback):
        globals().update(self.old)

def memoize(fn, slot=None, maxsize=32):
    """Memoize fn: make it remember the computed value for any argument list.
    If slot is specified, store result in that slot of first argument.
    If slot is false, use lru_cache for caching the values."""
    if slot:
        def memoized_fn(obj, *args): # What *args allows you to do is take in more arguments than the number of formal arguments that you previously defined.
            if hasattr(obj, slot):
                return getattr(obj, slot)
            else:
                val = fn(obj, *args)
                setattr(obj, slot, val)
                return val
    else:
        @functools.lru_cache(maxsize=maxsize)
        def memoized_fn(*args):
            return fn(*args)

    return memoized_fn

def name(obj):
    """Try to find some reasonable name for the object."""
    return (getattr(obj, 'name', 0) or getattr(obj, '__name__', 0) or
            getattr(getattr(obj, '__class__', 0), '__name__', 0) or
            str(obj))

def isnumber(x):
    """Is x a number?"""
    return hasattr(x, '__int__')

def issequence(x):
    """Is x a sequence?"""
    return isinstance(x, collections.abc.Sequence)

def print_table(table, header=None, sep='   ', numfmt='{}'):
    """Print a list of lists as a table, so that columns line up nicely.
    header, if specified, will be printed as the first row.
    numfmt is the format for all numbers; you might want e.g. '{:.2f}'.
    (If you want different formats in different columns,
    don't use print_table.) sep is the separator between columns."""
    justs = ['rjust' if isnumber(x) else 'ljust' for x in table[0]]

    if header:
        table.insert(0, header)

    table = [[numfmt.format(x) if isnumber(x) else x for x in row]
             for row in table]

    sizes = list(
        map(lambda seq: max(map(len, seq)),
            list(zip(*[map(str, row) for row in table]))))

    for row in table:
        print(sep.join(getattr(
            str(x), j)(size) for (j, size, x) in zip(justs, sizes, row)))

def open_data(name, mode='r'):
    aima_root = os.path.dirname(__file__)
    aima_file = os.path.join(aima_root, *['aima-data', name])

    return open(aima_file, mode=mode)

def failure_test(algorithm, tests):
    """Grades the given algorithm based on how many tests it passes.
    Most algorithms have arbitrary output on correct execution, which is difficult
    to check for correctness. On the other hand, a lot of algorithms output something
    particular on fail (for example, False, or None).
    tests is a list with each element in the form: (values, failure_output)."""
    from statistics import mean
    return mean(int(algorithm(x) != y) for x, y in tests)

# ______________________________________________________________________________
# Expressions

# See https://docs.python.org/3/reference/expressions.html#operator-precedence
# See https://docs.python.org/3/reference/datamodel.html#special-method-names

class Expr(object):
    """A mathematical expression with an operator and 0 or more arguments.
    op is a str like '+' or 'sin'; args are Expressions.
    Expr('x') or Symbol('x') creates a symbol (a nullary Expr).
    Expr('-', x) creates a unary; Expr('+', x, 1) creates a binary."""

    def __init__(self, op, *args):
        self.op = str(op)
        self.args = args

    # Operator overloads
    def __neg__(self):
        return Expr('-', self)

    def __pos__(self):
        return Expr('+', self)

    def __invert__(self):
        return Expr('~', self)

    def __add__(self, rhs):
        return Expr('+', self, rhs)

    def __sub__(self, rhs):
        return Expr('-', self, rhs)

    def __mul__(self, rhs):
        return Expr('*', self, rhs)

    def __pow__(self, rhs):
        return Expr('**', self, rhs)

    def __mod__(self, rhs):
        return Expr('%', self, rhs)

    def __and__(self, rhs):
        return Expr('&', self, rhs)

    def __xor__(self, rhs):
        return Expr('^', self, rhs)

    def __rshift__(self, rhs):
        return Expr('>>', self, rhs)

    def __lshift__(self, rhs):
        return Expr('<<', self, rhs)

    def __truediv__(self, rhs):
        return Expr('/', self, rhs)

    def __floordiv__(self, rhs):
        return Expr('//', self, rhs)

    def __matmul__(self, rhs):
        return Expr('@', self, rhs)

    def __or__(self, rhs):
        """Allow both P | Q, and P |'==>'| Q."""
        if isinstance(rhs, Expression):
            return Expr('|', self, rhs)
        else:
            return PartialExpr(rhs, self)

    # Reverse operator overloads
    def __radd__(self, lhs):
        return Expr('+', lhs, self)

    def __rsub__(self, lhs):
        return Expr('-', lhs, self)

    def __rmul__(self, lhs):
        return Expr('*', lhs, self)

    def __rdiv__(self, lhs):
        return Expr('/', lhs, self)

    def __rpow__(self, lhs):
        return Expr('**', lhs, self)

    def __rmod__(self, lhs):
        return Expr('%', lhs, self)

    def __rand__(self, lhs):
        return Expr('&', lhs, self)

    def __rxor__(self, lhs):
        return Expr('^', lhs, self)

    def __ror__(self, lhs):
        return Expr('|', lhs, self)

    def __rrshift__(self, lhs):
        return Expr('>>', lhs, self)

    def __rlshift__(self, lhs):
        return Expr('<<', lhs, self)

    def __rtruediv__(self, lhs):
        return Expr('/', lhs, self)

    def __rfloordiv__(self, lhs):
        return Expr('//', lhs, self)

    def __rmatmul__(self, lhs):
        return Expr('@', lhs, self)

    def __call__(self, *args):
        "Call: if 'f' is a Symbol, then f(0) == Expr('f', 0)."
        if self.args:
            raise ValueError('can only do a call for a Symbol, not an Expr')
        else:
            return Expr(self.op, *args)

    # Equality and repr
    def __eq__(self, other):
        "'x == y' evaluates to True or False; does not build an Expr."
        return (isinstance(other, Expr)
                and self.op == other.op
                and self.args == other.args)

    def __hash__(self):
        return hash(self.op) ^ hash(self.args)

    def __repr__(self):
        op = self.op
        args = [str(arg) for arg in self.args]
        if op.isidentifier():  # f(x) or f(x, y)
            return '{}({})'.format(op, ', '.join(args)) if args else op
        elif len(args) == 1:  # -x or -(x + 1)
            return op + args[0]
        else:  # (x - y)
            opp = (' ' + op + ' ')
            return '(' + opp.join(args) + ')'

# An 'Expression' is either an Expr or a Number.
# Symbol is not an explicit type; it is any Expr with 0 args.

Number = (int, float, complex)
Expression = (Expr, Number)

def Symbol(name):
    """A Symbol is just an Expr with no args."""
    return Expr(name)

def symbols(names):
    """Return a tuple of Symbols; names is a comma/whitespace delimited str."""
    return tuple(Symbol(name) for name in names.replace(',', ' ').split())

def subexpressions(x):
    """Yield the subexpressions of an Expression (including x itself)."""
    yield x
    if isinstance(x, Expr):
        for arg in x.args:
            yield from subexpressions(arg)

def arity(expression):
    """The number of sub-expressions in this expression."""
    if isinstance(expression, Expr):
        return len(expression.args)
    else:  # expression is a number
        return 0

# For operators that are not defined in Python, we allow new InfixOps:

class PartialExpr:
    """Given 'P |'==>'| Q, first form PartialExpr('==>', P), then combine with Q."""

    def __init__(self, op, lhs):
        self.op, self.lhs = op, lhs

    def __or__(self, rhs):
        return Expr(self.op, self.lhs, rhs)

    def __repr__(self):
        return "PartialExpr('{}', {})".format(self.op, self.lhs)

def expr(x):
    """Shortcut to create an Expression. x is a str in which:
    - identifiers are automatically defined as Symbols.
    - ==> is treated as an infix |'==>'|, as are <== and <=>.
    If x is already an Expression, it is returned unchanged. Example:
    >>> expr('P & Q ==> Q')
    ((P & Q) ==> Q)
    """
    if isinstance(x, str):
        return eval(expr_handle_infix_ops(x), defaultkeydict(Symbol))
    else:
        return x

infix_ops = '==> <== <=>'.split()

def expr_handle_infix_ops(x):
    """Given a str, return a new str with ==> replaced by |'==>'|, etc.
    >>> expr_handle_infix_ops('P ==> Q')
    "P |'==>'| Q"
    """
    for op in infix_ops:
        x = x.replace(op, '|' + repr(op) + '|')
    return x


class defaultkeydict(collections.defaultdict):
    """Like defaultdict, but the default_factory is a function of the key.
    >>> d = defaultkeydict(len); d['four']
    4
    """

    def __missing__(self, key):
        self[key] = result = self.default_factory(key)
        return result


class hashabledict(dict):
    """Allows hashing by representing a dictionary as tuple of key:value pairs
       May cause problems as the hash value may change during runtime
    """

    def __hash__(self):
        return 1

# ______________________________________________________________________________
# Queues: Stack, FIFOQueue, PriorityQueue
# Stack and FIFOQueue are implemented as list and collection.deque
# PriorityQueue is implemented here

class PriorityQueue:
    """A Queue in which the minimum (or maximum) element (as determined by f and
    order) is returned first.
    If order is 'min', the item with minimum f(x) is
    returned first; if order is 'max', then it is the item with maximum f(x).
    Also supports dict-like lookup."""

    def __init__(self, order='min', f=lambda x: x):
        self.heap = []

        if order == 'min':
            self.f = f
        elif order == 'max':  # now item with max f(x)
            self.f = lambda x: -f(x)  # will be popped first
        else:
            raise ValueError("order must be either 'min' or max'.")

    def append(self, item):
        """Insert item at its correct position."""
        heapq.heappush(self.heap, (self.f(item), item))

    def extend(self, items):
        """Insert each item in items at its correct position."""
        for item in items:
            self.heap.append(item)

    def pop(self):
        """Pop and return the item (with min or max f(x) value
        depending on the order."""
        if self.heap:
            return heapq.heappop(self.heap)[1]
        else:
            raise Exception('Trying to pop from empty PriorityQueue.')

    def __len__(self):
        """Return current capacity of PriorityQueue."""
        return len(self.heap)

    def __contains__(self, item):
        """Return True if item in PriorityQueue."""
        return (self.f(item), item) in self.heap

    def __getitem__(self, key):
        for _, item in self.heap:
            if item == key:
                return item

    def __delitem__(self, key):
        """Delete the first occurrence of key."""
        self.heap.remove((self.f(key), key))
        heapq.heapify(self.heap)

# ______________________________________________________________________________
# Useful Shorthands


class Bool(int):
    """Just like `bool`, except values display as 'T' and 'F' instead of 'True' and 'False'"""
    __str__ = __repr__ = lambda self: 'T' if self else 'F'

********************************prac3.py**************************************
from myutils import *

infinity = float('inf')

class Node:
    def __init__(self, state, parent=None, action=None, path_cost=0):
        self.state = state
        self.parent = parent
        self.action = action
        self.path_cost = path_cost
        self.depth = 0
        if parent:
            self.depth = parent.depth + 1

    def __repr__(self):
        return "<Node {}>".format(self.state)

    def expand(self, problem):
        return [self.child_node(problem, action)
                for action in problem.actions(self.state)]

    def child_node(self, problem, action):
        next_state = problem.result(self.state, action)
        next_node = Node(next_state, self, action,
                    problem.path_cost(self.path_cost, self.state,
                                      action, next_state))
        return next_node

    def solution(self):
        return [node.action for node in self.path()[1:]]

    def path(self):
        node, path_back = self, []
        while node:
            path_back.append(node)
            node = node.parent
        return list(reversed(path_back))

class Graph:
    def __init__(self, graph_dict=None, directed=True):
        self.graph_dict = graph_dict or {}
        self.directed = directed
        if not directed:
            self.make_undirected()

    def make_undirected(self):
        for a in list(self.graph_dict.keys()):
            for (b, dist) in self.graph_dict[a].items():
                self.connect1(b, a, dist)

    def connect1(self, A, B, distance):
        self.graph_dict.setdefault(A, {})[B] = distance

    def get(self, a, b=None):
        links = self.graph_dict.setdefault(a, {})
        if b is None:
            return links
        else:
            return links.get(b)

    def nodes(self):     
        s1 = set([k for k in self.graph_dict.keys()])
        s2 = set([k2 for v in self.graph_dict.values() for k2, v2 in v.items()])
        nodes = s1.union(s2)
        return list(nodes)

class Problem(object):
    def __init__(self, initial, goal=None):
       self.initial = initial
       self.goal = goal

    def actions(self, state):
         raise NotImplementedError

    def result(self, state, action):
        raise NotImplementedError

    def goal_test(self, state):
        if isinstance(self.goal, list):
            return is_in(state, self.goal)
        else:
            return state == self.goal

    def path_cost(self, c, state1, action, state2):
        return c + 1

    def value(self, state):
        raise NotImplementedError

def UndirectedGraph(graph_dict=None):
    return Graph(graph_dict = graph_dict, directed=False)

class GraphProblem(Problem):
    def __init__(self, initial, goal, graph):
        Problem.__init__(self, initial, goal)
        self.graph = graph

    def actions(self, A):
        return list(self.graph.get(A).keys())

    def result(self, state, action):
        return action

    def path_cost(self, cost_so_far, A, action, B):
        return cost_so_far + (self.graph.get(A, B) or infinity)

    def find_min_edge(self):
        m = infinity
        for d in self.graph.graph_dict.values():
            local_min = min(d.values())
            m = min(m, local_min)

        return m

    def h(self, node):
        """h function is straight-line distance from a node's state to goal."""
        locs = getattr(self.graph, 'locations', None)
        if locs:
            if type(node) is str:
                return int(distance(locs[node], locs[self.goal]))

            return int(distance(locs[node.state], locs[self.goal]))
        else:
            return infinity

def best_first_graph_search(problem, f):
    f = memoize(f, 'f')    
    node = Node(problem.initial)
    if problem.goal_test(node.state):
        return node
    frontier = PriorityQueue('min', f)
    frontier.append(node)
    explored = set()
    while frontier:
        node = frontier.pop()
        print("popping node : " , node)
        if problem.goal_test(node.state):
            return node
        explored.add(node.state)
        for child in node.expand(problem):
            print("adding child :", child)
            if child.state not in explored and child not in frontier:
                frontier.append(child)
            elif child in frontier:                
                incumbent = frontier[child]
                print(child , " in frontier. incumbent - ", incumbent)
                if f(child) < f(incumbent):
                    del frontier[incumbent]
                    frontier.append(child)
    return None

def astar_search(problem, h=None):

    h = memoize(h or problem.h, 'h')
    return best_first_graph_search(problem, lambda n: n.path_cost + h(n))

romania_map = UndirectedGraph(dict(

    Arad=dict(Zerind=75, Sibiu=140, Timisoara=118),
    Bucharest=dict(Urziceni=85, Pitesti=101, Giurgiu=90, Fagaras=211),
    Craiova=dict(Drobeta=120, Rimnicu=146, Pitesti=138),
    Drobeta=dict(Mehadia=75),
    Eforie=dict(Hirsova=86),
    Fagaras=dict(Sibiu=99),
    Hirsova=dict(Urziceni=98),
    Iasi=dict(Vaslui=92, Neamt=87),
    Lugoj=dict(Timisoara=111, Mehadia=70),
    Oradea=dict(Zerind=71, Sibiu=151),
    Pitesti=dict(Rimnicu=97),
    Rimnicu=dict(Sibiu=80),
    Urziceni=dict(Vaslui=142)))

romania_map.locations = dict(

    Arad=(91, 492), Bucharest=(400, 327), Craiova=(253, 288),
    Drobeta=(165, 299), Eforie=(562, 293), Fagaras=(305, 449),
    Giurgiu=(375, 270), Hirsova=(534, 350), Iasi=(473, 506),
    Lugoj=(165, 379), Mehadia=(168, 339), Neamt=(406, 537),
    Oradea=(131, 571), Pitesti=(320, 368), Rimnicu=(233, 410),
    Sibiu=(207, 457), Timisoara=(94, 410), Urziceni=(456, 350),
    Vaslui=(509, 444), Zerind=(108, 531))

romania_problem = GraphProblem('Arad','Bucharest', romania_map)

resultnode = astar_search(romania_problem)

print(resultnode.path())
print("Path Cost :" , resultnode.path_cost)


*****************************Practical 4***************************************
Implement recursive best-first search algorithm for Romanian map problem.
CODE:
from myutils import *

infinity = float('inf')

class Node:
    def __init__(self, state, parent=None, action=None, path_cost=0):
        self.state = state
        self.parent = parent
        self.action = action
        self.path_cost = path_cost
        self.f = 0
        self.depth = 0
        if parent:
            self.depth = parent.depth + 1

    def __repr__(self):
        return "<Node {}>".format(self.state)

    def expand(self, problem):
        return [self.child_node(problem, action)
                for action in problem.actions(self.state)]

    def child_node(self, problem, action):
        next_state = problem.result(self.state, action)
        new_cost = problem.path_cost(self.path_cost, self.state,action,next_state)
        next_node = Node(next_state, self, action,new_cost)
        return next_node

    def solution(self):
        return [node.action for node in self.path()]

    def path(self):
        node, path_back = self, []
        while node:
            path_back.append(node)
            node = node.parent
        return list(reversed(path_back))

class Graph:
    def __init__(self, graph_dict=None, directed=True):
        self.graph_dict = graph_dict or {}
        self.directed = directed
        if not directed:
            self.make_undirected()

    def make_undirected(self):
        for a in list(self.graph_dict.keys()):
            for (b, dist) in self.graph_dict[a].items():
                self.connect1(b, a, dist)

    def connect1(self, A, B, distance):
        self.graph_dict.setdefault(A, {})[B] = distance

    def get(self, a, b=None):
        links = self.graph_dict.setdefault(a, {})
        if b is None:
            return links
        else:
            return links.get(b)

class Problem(object):
    def __init__(self, initial, goal=None):
       self.initial = initial
       self.goal = goal

    def actions(self, state):
         raise NotImplementedError

    def result(self, state, action):
        raise NotImplementedError

    def goal_test(self, state):
        if isinstance(self.goal, list):
            return is_in(state, self.goal)
        else:
            return state == self.goal

    def path_cost(self, c, state1, action, state2):
        return c + 1

    def value(self, state):
        raise NotImplementedError

class GraphProblem(Problem):
    def __init__(self, initial, goal, graph):
        Problem.__init__(self, initial, goal)
        self.graph = graph

    def actions(self, A):
        return list(self.graph.get(A).keys())

    def result(self, state, action):
        return action

    def path_cost(self, cost_so_far, A, action, B):
        return cost_so_far + (self.graph.get(A, B) or infinity)

    def h(self, node):
        """h function is straight-line distance from a node's state to goal."""
        locs = getattr(self.graph, 'locations', None)
        if locs:
            if type(node) is str:
                return int(distance(locs[node], locs[self.goal]))
            return int(distance(locs[node.state], locs[self.goal]))
        else:
            return infinity

def UndirectedGraph(graph_dict=None):
    return Graph(graph_dict = graph_dict, directed=False)

def RecursiveBFS(problem): 
    return RBFS(problem, Node(problem.initial), infinity)

def RBFS(problem, node, f_limit):
    if problem.goal_test(node.state):
        return[node, None]
    successors = []
    for child in node.expand(problem):
        gval = child.path_cost
        hval = problem.h(child)
        child.f = gval + hval
        successors.append(child)

    if len(successors) == 0:
        return[None, infinity]

    while True:
        best = lowest_fvalue_node(successors)

        if best.f > f_limit:
            return [None, best.f]
        alternative = second_lowest_fvalue(successors, best.f)

        x = RBFS(problem, best, min(f_limit, alternative))
        result = x[0]
        best.f = x[1]

        if result!=None:
            return[result, None]

def second_lowest_fvalue(nodelist, lowest_f):
    secondmin_fval = infinity
    for n in range(0, len(nodelist)):
        if nodelist[n].f > lowest_f and nodelist[n].f < secondmin_fval:
            secondmin_fval = nodelist[n].f
    return secondmin_fval

def lowest_fvalue_node(nodelist):
    min_fval = nodelist[0].f
    min_fval_node_index = 0
    for n in range(1, len(nodelist)):
        if nodelist[n].f < min_fval:
            min_fval_node_index = n
            min_fval = nodelist[n].f
    return nodelist[min_fval_node_index]

romania_map = UndirectedGraph(dict(
    Arad=dict(Zerind=75, Sibiu=140, Timisoara=118),
    Bucharest=dict(Urziceni=85, Pitesti=101, Giurgiu=90, Fagaras=211),
    Craiova=dict(Drobeta=120, Rimnicu=146, Pitesti=138),
    Drobeta=dict(Mehadia=75),
    Eforie=dict(Hirsova=86),
    Fagaras=dict(Sibiu=99),
    Hirsova=dict(Urziceni=98),
    Iasi=dict(Vaslui=92, Neamt=87),
    Lugoj=dict(Timisoara=111, Mehadia=70),
    Oradea=dict(Zerind=71, Sibiu=151),
    Pitesti=dict(Rimnicu=97),
    Rimnicu=dict(Sibiu=80),
    Urziceni=dict(Vaslui=142)))

romania_map.locations = dict(

    Arad=(91, 492), Bucharest=(400, 327), Craiova=(253, 288),
    Drobeta=(165, 299), Eforie=(562, 293), Fagaras=(305, 449),
    Giurgiu=(375, 270), Hirsova=(534, 350), Iasi=(473, 506),
    Lugoj=(165, 379), Mehadia=(168, 339), Neamt=(406, 537),
    Oradea=(131, 571), Pitesti=(320, 368), Rimnicu=(233, 410),
    Sibiu=(207, 457), Timisoara=(94, 410), Urziceni=(456, 350),
    Vaslui=(509, 444), Zerind=(108, 531))

print("\nSolving for Arad to Bucharest...")
romania_problem = GraphProblem('Arad','Bucharest', romania_map)

resultnode = RecursiveBFS(romania_problem)

if(resultnode[0] != None):
    print("Path taken: ", resultnode[0].path())
    print("Path cost: ", resultnode[0].path_cost)

*********************************Practical 5****************************************
Aim: Implement decision tree learning algorithm for the restaurant waiting problem.
CODE:
import math

class DataSet:
    def __init__(self,ds):
        self.dataset = ds

    def print(self):
        print(self.dataset)

    def uniqueAns(self) :
        ans_set = set(self.dataset["Ans"])
        return len(ans_set)

    def getMaxOccur(self):
        d = {self.dataset["Ans"].count(x):x
             for x in self.dataset["Ans"]}
        keys = list(d.keys())
        keys.sort(reverse=True)

        if len(keys) >1 and keys[0] != keys[1]:
            return d[keys[0]]
        else:
            return None


    def copy(self):
        newdataset = dict()
        keys = list(self.dataset.keys())
        newdataset = dict.fromkeys(keys,0)
        for key in keys :
            newdataset[key] = self.dataset[key].copy()
        return DataSet(newdataset)

    def maxInfoGain(self):    
        features = self.dataset["Features"]
        if len(features) >=0 :
            maxinfogain = self.infoGain(features[0])
            maxfeat = features[0]
            i=0
            while i<len(features):
                ig = self.infoGain(features[i])                
                if ig>=maxinfogain :
                    maxinfogain = ig
                    maxfeat = features[i]
                i = i + 1
            return maxfeat
        else:
            return None

    def infoGain(self, feat) :
        if feat in self.dataset.keys() :
            featlist1 = self.dataset[feat]
            total = len(featlist1)
            featset = set(featlist1)
            d = dict.fromkeys(featset, 0)
            for item in featlist1 :
                d[item] = d[item]+1
            branches = self.splitOnFeature(feat)
            gain = 0
            for key in branches :
               dsobj = branches[key]
               gain = gain  + ( (d[key] / total) *( dsobj.getEntropy()) )
            return self.getEntropy() - gain
        else :
            print("feature does not exists")
            return None

    def getEntropy(self) :
        list1 = self.dataset["Ans"]
        total = len(list1)
        aset = set(list1)
        d = dict.fromkeys(aset, 0)        
        for item in list1 :
            d[item] = d[item]+1
        ent = 0
        for k in aset :
            x = d[k]/total
            ent = ent + (x * math.log(x,2))        
        return -ent
  def splitOnFeature(self, feat):
     if feat in self.dataset["Features"] :
            ans_set = set(self.dataset[feat])
            newfeatures = self.dataset["Features"].copy()
            newfeatures.remove(feat)
            keys = list(self.dataset.keys())            
            newdataset = dict()
            for akey in keys :
                newdataset[akey] = list()            
            newdataset["Features"] = newfeatures.copy()            
            newdataset.pop(feat)
            branches = dict()
            for akey in ans_set:                
                branches[akey] = dict()
                for key in list(newdataset.keys()) :                
                    branches[akey][key] = newdataset[key].copy()

            i=-1           
            for featval in self.dataset[feat]:
                i=i+1
                if featval in list(branches.keys()) :
                    branches[featval]["Ans"].append(self.dataset["Ans"][i])
                    for nfeat in newfeatures :
                        branches[featval][nfeat].append(self.dataset[nfeat][i])
            for key in branches :
                  branches[key] = DataSet(branches[key])
            return branches
     else:
            print(feat , " feature is not available")
            return None

def calculateAns(dsobj, feature, maxoccur, descr ):
    branches  = dsobj.splitOnFeature(feature)
    for key in list(branches.keys()):
        newdsobj = branches[key]
    for key in list(branches.keys()):

        newdsobj = branches[key]

        if (newdsobj.uniqueAns() == 1):
            print("Answer for " , descr+"-" +feature ,
            " with value =", key , " is :",
            newdsobj.dataset['Ans'][0])
        elif(newdsobj.uniqueAns() == 0):
            print("in zero")
            print("Answer for " , descr+"-" +feature ,
            " with value =", key , " is :", maxoccur)            
        elif(newdsobj.uniqueAns() >1
            and len(newdsobj.dataset["Features"]) ==0 ) :
            print("Answer for " , descr+"-" +feature ,
            " with value =", key , " is :", maxoccur)            
        else:            
            newfeat = newdsobj.maxInfoGain()
            newmaxoccur = newdsobj.getMaxOccur()
            if(newmaxoccur == None) :
                newmaxoccur = maxoccur
            calculateAns(newdsobj, newfeat, newmaxoccur , descr + ":" + feature +":->" + key +" " )            

dataset = {
        "Ans" :["Wait", "Wait", "Leave", "Wait", "Wait", "Wait", "Leave", "Leave", "Wait", "Leave"],
        "Features":["Reservation", "Raining", "BadService"],
        "Reservation" : ["T", "T", "T", "F", "T", "T", "T", "T", "T", "F"],
        "Raining" : ["T", "F", "T", "T", "T","T", "F", "T", "T", "F"],
        "BadService":["F", "F", "T", "F", "F","F", "T", "T", "F", "F"]
        }

d1 = DataSet(dataset)

if d1.uniqueAns() != 1 :

    feat = d1.maxInfoGain()
    calculateAns(d1, feat, d1.getMaxOccur(), "")

********************************Practical 6********************************** 
Aim: Implement feed forward back propagation neural network learning algorithm for the 
restaurant waiting problem. 
CODE: 
class Perceptron :    
    def __init__(self, a,b, c, tval): 
        self.x = a 
        self.result = b 
        self.cresult = c 
        self.threshold = tval  
        self.w = [] 

    def h(self, tw): 
        hresult= [] 
        for i in range(0 , len(self.result)): 
            hresult.append(0) 
            for j in range(0,len(tw)): 
                hresult[i] = hresult[i] + ( tw[j][i]*self.x[j][i] )  
        return hresult 

    def checkthreshold(self, hresult): 
        actfun =[] 
        for i in range(0 , len(self.result)) :             
            if (hresult[i] <= self.threshold ): 
                actfun.append(0) 
            else : 
                actfun.append( 1) 
        print("Ans :", hresult) 
        print("result of act fun:", actfun) 

        for i in range(0 , len(self.x)) : 
            if (actfun[i] != self.result[i]) : 
                return False 
        return True 

    def training(self, tw, alpha): 
        i=1 
        while i<=100 : 
                print("Attempt :", i) 
                hresult = self.h(tw)             
                if(self.checkthreshold(hresult)) : 
                    self.w = tw                                      
                    print("In Attempt number ", i,  ", i got it! I think i have learnt enough. Your w's are --" ) 
                    for x in range(0,len(self.w)): 
                        print("w", x, " --> ", self.w[x]) 
                    break 
                i = i +1       
                for j in range(0,len(self.result)) : 
                    for k in range(0, len(tw)): 
                        sum = 0 
                        for n in range(0, len(tw)):     
                             sum = sum + (self.cresult[j] - hresult[j]) *self.x[n][j]                         
                        tw[k][j] = tw[k][j] + alpha*sum                         
        if(i>=100): 
            print("I am exhausted, tried 100 iterations! plz change something else...") 

a = [ [1,1,1,1], [0,0,1,1] , [0,1,0,1] ]  
b = [0,1,1,1] 
c = [0.5, 0.7, 1.3, 1.5] 
p = Perceptron(a,b,c, 0.5) 

print("Whether reservation is done =", p.x[0]) 
print("Whether raining outside =", p.x[1]) 
print("with threshold value :", p.threshold) 

r =  p.h([ [0.5,0.5,0.5,0.5], [0.8, 0.8, 0.8, 0.8], [0.2, 0.2, 0.2, 0.2]]) 
print("status :", p.checkthreshold(r)) 

print("Example 1 -->") 
p.training( [ [0.7,0.7,0.7,0.7], [0.5, 0.5, 0.5, 0.5], [0.4, 0.4, 0.4, 0.4]], 0.01) 

print("Example 2 -->") 
p.training( [ [0.7,0.7,0.7,0.7], [0.5, 0.5, 0.5, 0.5], [0.4, 0.4, 0.4, 0.4]], 0.5) 

print("Example 3 -->") 
p.training( [ [0.2,0.2,0.2,0.2], [0.3, 0.3, 0.3, 0.3], [0.5, 0.5, 0.5, 0.5]], 0.01) 

*************************Practical 7****************************************

Aim: -Implement Adaboost ensemble learning algorithm.
In Command Prompt:
pip install pandas
pip install scikit-learn

a)    Apple and Orange dataset
Step 1 : - Download apple_and_oranges.csv and add them into the program folder.

apples_and_oranges.csv 
CODE:
import pandas as pd
data = pd.read_csv("apples_and_oranges.csv")
print(data)
from sklearn.model_selection import train_test_split
training_set, test_set = train_test_split(data, test_size = 0.2, random_state = 1)

X_train = training_set.iloc[:,0:2].values 
Y_train = training_set.iloc[:,2].values 
X_test = test_set.iloc[:,0:2].values
Y_test = test_set.iloc[:,2].values

from sklearn.ensemble import AdaBoostClassifier
adaboost = AdaBoostClassifier(n_estimators=100, estimator= None,learning_rate=1, random_state = 1)

adaboost.fit(X_train,Y_train)
Y_pred = adaboost.predict(X_test)
test_set["Predictions"] = Y_pred

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(Y_test,Y_pred)
accuracy = float(cm.diagonal().sum())/len(Y_test)
print("\nAccuracy Of AdaBoost For The Given Dataset : ", accuracy)

OUTPUT: 

b)    Restaurant Waiting Problem
import pandas as pd

data = pd.read_csv("restaurant_waiting.csv")
print(data)

from sklearn.model_selection import train_test_split
training_set, test_set = train_test_split(data, test_size = 0.2, random_state = 1)

X_train = training_set.iloc[:,0:2].values 
Y_train = training_set.iloc[:,2].values 

X_test = test_set.iloc[:,0:2].values
Y_test = test_set.iloc[:,2].values

from sklearn.ensemble import AdaBoostClassifier
adaboost = AdaBoostClassifier(n_estimators=100, estimator= None,learning_rate=1, random_state = 1)

adaboost.fit(X_train,Y_train)
Y_pred = adaboost.predict(X_test)
test_set["Predictions"] = Y_pred

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(Y_test,Y_pred)
accuracy = float(cm.diagonal().sum())/len(Y_test)
print("\nAccuracy Of AdaBoost For The Given Restaurant Waiting Problem : ", accuracy)

OUTPUT:
  
******************************Practical No. 8*********************************
 AIM: Implement Naive Bayes’ Learning Algorithm for:
In Command Prompt:
pip install scikit-learn

a)    Built-in Dataset 
Code:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score

iris = load_iris()
x = iris.data
y = iris.target

x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2, random_state=42)
clf = GaussianNB()

clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)

accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")

OUTPUT:
b)    Football Matches Dataset
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
import pandas as pd
# load the football data from csv
dataset = pd.read_csv('matches.csv')
x = dataset[['Argentina', 'France']].values
y = dataset['Result'].values
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2, random_state=42)
clf = GaussianNB()
clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)
print(x)
print(y)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
OUTPUT:

c)    Restaurant Waiting Problem
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
import pandas as pd

dataset = pd.read_csv('restaurant_waiting.csv')

x = dataset[['Reservation','Raining','BadService']].values
y = dataset['Result'].values

x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2, random_state=42)
clf = GaussianNB()

clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)

print(x)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")


OUTPUT: