0% found this document useful (0 votes)
27 views

Ai Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Ai Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

1a.

WRITE A PROGRAM TO IMPLEMENT BREADTH FIRST SEARCH

PROGRAM:

graph = {

‘A’ : [‘B’,’C’],

‘B’ : [‘D’, ‘E’],

‘C’ : [‘F’],

‘D’ : [],

‘E’ : [‘F’],

‘F’ : []

visited = [] # List to keep track of visited nodes.

Queue = [] #Initialize a queue

def bfs(visited, graph, node):

visited.append(node)

queue.append(node)

while queue:

s = queue.pop(0)

print (s, end = “ “)

for neighbour in graph[s]:

if neighbour not in visited:

visited.append(neighbour)

queue.append(neighbour)

bfs(visited, graph, ‘A’)

NAME: H.T.NO: SUB.NAME:


OUTPUT:

ABCDEF

NAME: H.T.NO: SUB.NAME:


1b.WRITE A PROGRAM TO IMPLEMENT DEPTH FIRST SEARCH

PROGRAM:

graph = {

'5' : ['3','7'],

'3' : ['2', '4'],

'7' : ['8'],

'2' : [],

'4' : ['8'],

'8' : []

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs

if node not in visited:

print (node)

visited.add(node)

for neighbour in graph[node]:

dfs(visited, graph, neighbour)

# Driver Code

print("Following is the Depth-First Search")

dfs(visited, graph, '5')

NAME: H.T.NO: SUB.NAME:


OUTPUT:

Following is the Depth-First Search


5
3
2
4
8
7

NAME: H.T.NO: SUB.NAME:


2. WRITE A PROGRAM TO FIND THE SOLUTION FOR TRAVELLING
SALESMAN

PROGRAM:

from sys import maxsize

from itertools import permutations

V=4

# implementation of traveling Salesman Problem

def travellingSalesmanProblem(graph, s):

# store all vertex apart from source vertex

vertex = []

for i in range(V):

if i != s:

vertex.append(i)

# store minimum weight Hamiltonian Cycle

min_path = maxsize

next_permutation=permutations(vertex)

for i in next_permutation:

# store current Path weight(cost)

current_pathweight = 0

# compute current path weight

k=s

for j in i:

current_pathweight += graph[k][j]

k=j

current_pathweight += graph[k][s]

# update minimum

NAME: H.T.NO: SUB.NAME:


min_path = min(min_path, current_pathweight)

return min_path

if __name__ == "__main__":

# matrix representation of graph

graph = [[0, 10, 15, 20], [10, 0, 35, 25],

[15, 35, 0, 30], [20, 25, 30, 0]]

s=0

print(travellingSalesmanProblem(graph, s))

OUTPUT:

80/55

NAME: H.T.NO: SUB.NAME:


3. WRITE A PROGRAM TO IMPLEMENT SIMULATED ANNEALING
ALGORITHM

PROGRAM:

# convex unimodal optimization function

from numpy import arange

from matplotlib import pyplot

# objective function

def objective(x):

return x[0]**2.0

# define range for input

r_min, r_max = -5.0, 5.0

# sample input range uniformly at 0.1 increments

inputs = arange(r_min, r_max, 0.1)

# compute targets

results = [objective([x]) for x in inputs]

# create a line plot of input vs result

pyplot.plot(inputs, results)

# define optimal input value

x_optima = 0.0

# draw a vertical line at the optimal input

pyplot.axvline(x=x_optima, ls='--', color='red')

# show the plot

pyplot.show()

# explore temperature vs algorithm iteration for simulated annealing

from matplotlib import pyplot

# total iterations of algorithm

NAME: H.T.NO: SUB.NAME:


iterations = 100

# initial temperature

initial_temp = 10

# array of iterations from 0 to iterations - 1

iterations = [i for i in range(iterations)]

# temperatures for each iterations

temperatures = [initial_temp/float(i + 1) for i in iterations]

# plot iterations vs temperatures

pyplot.plot(iterations, temperatures)

pyplot.xlabel('Iteration')

pyplot.ylabel('Temperature')

pyplot.show()

# explore metropolis acceptance criterion for simulated annealing

from math import exp

from matplotlib import pyplot

# total iterations of algorithm

iterations = 100

# initial temperature

initial_temp = 10

# array of iterations from 0 to iterations - 1

iterations = [i for i in range(iterations)]

# temperatures for each iterations

temperatures = [initial_temp/float(i + 1) for i in iterations]

# metropolis acceptance criterion

differences = [0.01, 0.1, 1.0]

NAME: H.T.NO: SUB.NAME:


for d in differences:

metropolis = [exp(-d/t) for t in temperatures]

# plot iterations vs metropolis

label = 'diff=%.2f' % d

pyplot.plot(iterations, metropolis, label=label)

# inalize plot

pyplot.xlabel('Iteration')

pyplot.ylabel('Metropolis Criterion')

pyplot.legend()

pyplot.show()

NAME: H.T.NO: SUB.NAME:


OUTPUT:

NAME: H.T.NO: SUB.NAME:


NAME: H.T.NO: SUB.NAME:
4. THE WUMPUS WORLD PROBLEM
PROGRAM:

class WumpusWorldSolver:
def __init__(self, size):
self.size = size
self.grid = [[' ' for _ in range(size)] for _ in range(size)]
self.agent_location = (0, 0)
self.has_gold = False
self.has_wumpus = False
self.has_arrow = True

def print_world(self):
for row in self.grid:
print(row)

def move(self, direction):


x, y = self.agent_location
if direction == 'UP' and x > 0:
self.agent_location = (x - 1, y)
elif direction == 'DOWN' and x < self.size - 1:
self.agent_location = (x + 1, y)
elif direction == 'LEFT' and y > 0:
self.agent_location = (x, y - 1)
elif direction == 'RIGHT' and y < self.size - 1:
self.agent_location = (x, y + 1)

NAME: H.T.NO: SUB.NAME:


def grab(self):
if self.agent_location == (0, 1) and self.grid[0][1] == 'G':
self.has_gold = True
print("Gold grabbed!")

def shoot(self):
if self.has_arrow:
self.has_arrow = False
print("Arrow shot!")

def solve(self):
if self.agent_location == (0, 0):
self.move('RIGHT')
elif self.agent_location == (0, 1) and not self.has_gold:
self.grab()
elif self.agent_location == (0, 1) and self.has_gold:
self.move('LEFT')
elif self.agent_location == (0, 0):
self.move('UP')
else:
self.move('RIGHT')

# Example usage:
world = WumpusWorldSolver(size=4)
world.grid[1][1] = 'P' # Wumpus
world.grid[2][2] = 'G' # Gold
world.print_world()
world.solve()

NAME: H.T.NO: SUB.NAME:


world.print_world()

OUTPUT:

[' ', ' ', ' ', ' ']

[' ', 'P', ' ', ' ']

[' ', ' ', 'G', ' ']

[' ', ' ', ' ', ' ']

[' ', ' ', ' ', ' ']

[' ', 'P', ' ', ' ']

[' ', ' ', 'G', ' ']

[' ', ' ', ' ', ' ']

NAME: H.T.NO: SUB.NAME:


5. WRITE A PROGRAM TO IMPLEMENT 8 PUZZLE PROBLEM

PROGRAM:
import copy

from heapq import heappush, heappop

n=3

row = [ 1, 0, -1, 0 ]

col = [ 0, -1, 0, 1 ]

class priorityQueue:

def __init__(self):

self.heap = []

def push(self, k):

heappush(self.heap, k)

def pop(self):

return heappop(self.heap)

def empty(self):

if not self.heap:

return True

else:

return False

class node:

def __init__(self, parent, mat, empty_tile_pos,cost, level):

self.parent = parent

self.mat = mat

NAME: H.T.NO: SUB.NAME:


self.empty_tile_pos = empty_tile_pos

self.cost = cost

self.level = level

def __lt__(self, nxt):

return self.cost < nxt.cost

def calculateCost(mat, final) -> int:

count = 0

for i in range(n):

for j in range(n):

if ((mat[i][j]) and

(mat[i][j] != final[i][j])):

count += 1

return count

def newNode(mat, empty_tile_pos, new_empty_tile_pos,level, parent, final) ->


node:

new_mat = copy.deepcopy(mat)

x1 = empty_tile_pos[0]

y1 = empty_tile_pos[1]

x2 = new_empty_tile_pos[0]

y2 = new_empty_tile_pos[1]

new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2], new_mat[x1][y1]

cost = calculateCost(new_mat, final)

new_node = node(parent, new_mat, new_empty_tile_pos,cost, level)

return new_node

def printMatrix(mat):

for i in range(n):

NAME: H.T.NO: SUB.NAME:


for j in range(n):

print("%d " % (mat[i][j]), end = " ")

print()

def isSafe(x, y):

return x >= 0 and x < n and y >= 0 and y < n

def printPath(root):

if root == None:

return

printPath(root.parent)

printMatrix(root.mat)

print()

def solve(initial, empty_tile_pos, final):

pq = priorityQueue()

cost = calculateCost(initial, final)

root = node(None, initial,empty_tile_pos, cost, 0)

pq.push(root)

while not pq.empty():

minimum = pq.pop()

if minimum.cost == 0:

printPath(minimum)

return

for i in range(n):

new_tile_pos = [

minimum.empty_tile_pos[0] + row[i],

minimum.empty_tile_pos[1] + col[i], ]

NAME: H.T.NO: SUB.NAME:


if isSafe(new_tile_pos[0], new_tile_pos[1]):

child = newNode(minimum.mat,

minimum.empty_tile_pos,

new_tile_pos,

minimum.level + 1,

minimum, final,)

pq.push(child)

initial = [ [ 1, 2, 3 ],

[ 5, 6, 0 ],

[ 7, 8, 4 ] ]

final = [ [ 1, 2, 3 ],

[ 5, 8, 6 ],

[ 0, 7, 4 ] ]

empty_tile_pos = [ 1, 2 ]

solve(initial, empty_tile_pos, final)

NAME: H.T.NO: SUB.NAME:


OUTPUT:

123
560
784

123
506
784

123
586
704

123
586
074

NAME: H.T.NO: SUB.NAME:


6.WRITE A PROGRAM TO IMPLEMENT TOWERS OF HANOI
PROBLEM

PROGRAM:

class Tower:

def __init__(self):

self.terminate = 1

def printMove(self, source, destination):

print("{} -> {}".format(source, destination))

def move(self, disc, source, destination, auxiliary):

if disc == self.terminate:

self.printMove(source, destination)

else:

self.move(disc - 1, source, auxiliary, destination)

self.move(1, source, destination, auxiliary)

self.move(disc - 1, auxiliary, destination, source)

t = Tower();

t.move(3, 'A', 'B', 'C')

NAME: H.T.NO: SUB.NAME:


OUTPUT:

A -> B

A -> C

B -> C

A -> B

C -> A

C -> B

A -> B

NAME: H.T.NO: SUB.NAME:


1b.WRITE A PROGRAM TO IMPLEMENT DEPTH FIRST SEARCH

PROGRAM:

graph = {

'5' : ['3','7'],

'3' : ['2', '4'],

'7' : ['8'],

'2' : [],

'4' : ['8'],

'8' : []

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs

if node not in visited:

print (node)

visited.add(node)

for neighbour in graph[node]:

NAME: H.T.NO: SUB.NAME:


dfs(visited, graph, neighbour)

# Driver Code

print("Following is the Depth-First Search")

dfs(visited, graph, '5')

OUTPUT:

Following is the Depth-First Search


5
3
2
4
8
7

NAME: H.T.NO: SUB.NAME:


7.WRITE A PROGRAM TO IMPLEMENT A* ALGORITHM

PROGRAM:

from queue import PriorityQueue


#Creating Base Class
class State(object):
def __init__(self, value, parent, start = 0, goal = 0):
self.children = []
self.parent = parent
self.value = value
self.dist = 0
if parent:
self.start = parent.start
self.goal = parent.goal
self.path = parent.path[:]
self.path.append(value)
else:
self.path = [value]
self.start = start
self.goal = goal
def GetDistance(self):
pass
def CreateChildren(self):
pass

# Creating subclass

class State_String(State):
def __init__(self, value, parent, start = 0, goal = 0 ):
super(State_String, self).__init__(value, parent, start, goal)

NAME: H.T.NO: SUB.NAME:


self.dist = self.GetDistance()
def GetDistance(self):
if self.value == self.goal:
return 0
dist = 0
for i in range(len(self.goal)):
letter = self.goal[i]
dist += abs(i - self.value.index(letter))
return dist
def CreateChildren(self):
if not self.children:
for i in range(len(self.goal)-1):
val = self.value
val = val[:i] + val[i+1] + val[i] + val[i+2:]
child = State_String(val, self)
self.children.append(child)
# Creating a class that hold the final magic
class A_Star_Solver:
def __init__(self, start, goal):
self.path = []
self.vistedQueue =[]
self.priorityQueue = PriorityQueue()
self.start = start
self.goal = goal
def Solve(self):
startState = State_String(self.start,0,self.start,self.goal)
count = 0
self.priorityQueue.put((0,count, startState))
while(not self.path and self.priorityQueue.qsize()):
closesetChild = self.priorityQueue.get()[2]

NAME: H.T.NO: SUB.NAME:


closesetChild.CreateChildren()
self.vistedQueue.append(closesetChild.value)
for child in closesetChild.children:
if child.value not in self.vistedQueue:
count += 1
if not child.dist:
self.path = child.path
break
self.priorityQueue.put((child.dist,count,child))
if not self.path:
print("Goal Of is not possible !" + self.goal )
return self.path
# Calling all the existing stuffs
if __name__ == "__main__":
start1 = "BHANU"
goal1 = "NHUBA"
print("Starting....")
a = A_Star_Solver(start1,goal1)
a.Solve()
for i in range(len(a.path)):
print("{0}){1}".format(i,a.path[i]))

OUTPUT:

NAME: H.T.NO: SUB.NAME:


Starting

0)BHANU

1)BHNAU

2)BHNUA

3)HBNUA

4)HNBUA

5)NHBUA

6)NHUBA

NAME: H.T.NO: SUB.NAME:


1b.WRITE A PROGRAM TO IMPLEMENT DEPTH FIRST SEARCH

PROGRAM:

graph = {

'5' : ['3','7'],

'3' : ['2', '4'],

'7' : ['8'],

'2' : [],

'4' : ['8'],

'8' : []

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs

if node not in visited:

print (node)

visited.add(node)

NAME: H.T.NO: SUB.NAME:


for neighbour in graph[node]:

dfs(visited, graph, neighbour)

# Driver Code

print("Following is the Depth-First Search")

dfs(visited, graph, '5')

OUTPUT:

Following is the Depth-First Search


5
3
2
4
8
7

NAME: H.T.NO: SUB.NAME:


8. WRITE A PROGRAM TO IMPLEMENT HILL CLIMBING
ALGORITHM

PROGRAM:

# hill climbing search of the ackley objective function


from numpy import asarray
from numpy import exp
from numpy import sqrt
from numpy import cos
from numpy import e
from numpy import pi
from numpy.random import randn
from numpy.random import rand
from numpy.random import seed
# objective function
def objective(v):
x, y = v
return -20.0 * exp(-0.2 * sqrt(0.5 * (x**2 + y**2))) - exp(0.5 * (cos(2 * pi *
x) + cos(2 *
pi * y))) + e + 20

# check if a point is within the bounds of the search


def in_bounds(point, bounds):
# enumerate all dimensions of the point
for d in range(len(bounds)):
# check if out of bounds for this dimension
if point[d] < bounds[d, 0] or point[d] > bounds[d, 1]:
return False
return True
# hill climbing local search algorithm
def hillclimbing(objective, bounds, n_iterations, step_size):

NAME: H.T.NO: SUB.NAME:


# generate an initial point
solution = None
while solution is None or not in_bounds(solution, bounds):
solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
# evaluate the initial point
solution_eval = objective(solution)
# run the hill climb
for i in range(n_iterations):
# take a step
candidate = None
while candidate is None or not in_bounds(candidate, bounds):
candidate = solution + randn(len(bounds)) * step_size
# evaluate candidate point
candidte_eval = objective(candidate)
# check if we should keep the new point
if candidte_eval <= solution_eval:
# store the new point
solution, solution_eval = candidate, candidte_eval
#report progress
print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
return [solution, solution_eval]

# seed the pseudorandom number generator


seed(1)
# define range for input
bounds = asarray([[-5.0, 5.0], [-5.0, 5.0]])
# define the total iterations
n_iterations = 1000
# define the maximum step size
step_size = 0.05

NAME: H.T.NO: SUB.NAME:


# perform the hill climbing search
best, score = hillclimbing(objective, bounds, n_iterations, step_size)
print('Done!')
print('f(%s) = %f' % (best, score))

NAME: H.T.NO: SUB.NAME:


OUTPUT:

Starting

>0 f([-0.85618854 2.1495965 ]) = 6.46986

>1 f([-0.81291816 2.03451957]) = 6.07149

>5 f([-0.82903902 2.01531685]) = 5.93526

>7 f([-0.83766043 1.97142393]) = 5.82047

>9 f([-0.89269139 2.02866012]) = 5.68283

>12 f([-0.8988359 1.98187164]) = 5.55899

>13 f([-0.9122303 2.00838942]) = 5.55566

>14 f([-0.94681334 1.98855174]) = 5.43024

>15 f([-0.98117198 1.94629146]) = 5.39010

>23 f([-0.97516403 1.97715161]) = 5.38735

>39 f([-0.98628044 1.96711371]) = 5.38241

>362 f([-0.9808789 1.96858459]) = 5.38233

>629 f([-0.98102417 1.96555308]) = 5.38194

Done!

f([-0.98102417 1.96555308]) = 5.381939

NAME: H.T.NO: SUB.NAME:


10. BUILD A BOT THAT PROVIDES ALL THE INFORMATION
RELATED TO YOUR COLLEGE

PROGRAM:

def greet(bot_name, birth_year):


print("Hello! My name is {0}.".format(bot_name))
print("I was created in {0}.".format(birth_year))
def remind_name():
print('Please, remind me your name.')
name = input()
print("What a great name you have, {0}!".format(name))
def guess_age():
print('Let me guess your age.')
print('Enter remainders of dividing your age by 3, 5 and 7.')
rem3 = int(input())
rem5 = int(input())
rem7 = int(input())
age = (rem3 * 70 + rem5 * 21 + rem7 * 15) % 105
print("Your age is {0}; that's a good time to start
programming!".format(age))
def count():
print('Now I will prove to you that I can count to any number you want.')
num = int(input())
counter = 0
while counter <= num:
print("{0} !".format(counter))
counter += 1
def test():
print("Let's test your programming knowledge.")
print("Why do we use methods?")
print("1. To repeat a statement multiple times.")

NAME: H.T.NO: SUB.NAME:


print("2. To decompose a program into several small subroutines.")
print("3. To determine the execution time of a program.")
print("4. To interrupt the execution of a program.")
answer = 2
guess = int(input())
while guess != answer:
print("Please, try again.")
guess = int(input())
print('Completed, have a nice day!')
print('.................................')
print('.................................')
print('.................................')
def end():
print('Congratulations, have a nice day!')
print('.................................')
print('.................................')
print('.................................')
input()
greet('Sbot', '2021') # change it as you need
remind_name()
guess_age()
count()
test()
end()

NAME: H.T.NO: SUB.NAME:


OUTPUT:

Hello! My name is Sbot.

I was created in 2021.

Please, remind me your name.

III YEAR CSE(A&B)

What a great name you have, III YEAR CSE(A&B)!

Let me guess your age.

Enter remainders of dividing your age by 3, 5 and 7.

18

15

16

Your age is 30; that's a good time to start programming!

Now I will prove to you that I can count to any number you want.

10

0!

1!

2!

3!

4!

5!

6!

7!

8!

9!

10 !

NAME: H.T.NO: SUB.NAME:


Let's test your programming knowledge.

Why do we use methods?

1. To repeat a statement multiple times.

2. To decompose a program into several small subroutines.

3. To determine the execution time of a program.

4. To interrupt the execution of a program.

Please, try again.

Completed, have a nice day!

.................................

.................................

.................................

Congratulations, have a nice day!

.................................

.................................

.................................

NAME: H.T.NO: SUB.NAME:


11. BUILD A VIRTUAL ASSISTANT FOR WIKIPEDIA USING
WOLFRAM ALPHA AND PYTHON

PROGRAM:

import wolframalpha

# Taking input from user

question = input('Question: ')

# App id obtained by the above steps

#app_id = ‘Your app_id’

app_id = '7W243X-4EHR4PWX26'

# Instance of wolf ram alpha

# client class

client = wolframalpha.Client(app_id)

# Stores the response from

# wolf ram alpha

res = client.query(question)

# Includes only text from the response

answer = next(res.results).text

print(answer)

NAME: H.T.NO: SUB.NAME:


OUTPUT:

Question: What is the capital of India?

New Delhi, Delhi, India

Question: Who Is Father of Computer?

Charles Babbage

NAME: H.T.NO: SUB.NAME:


12.COUNTS THE NUMBER OF TIMES A STRING OCCURS IN
ANOTHER STRING

PROGRAM:

def count(a, b, m, n):

# If both first and second string

# is empty, or if second string

# is empty, return 1

if ((m == 0 and n == 0) or n == 0):

return 1

# If only first string is empty

# and second string is not empty,

# return 0

if (m == 0):

return 0

# If last characters are same

# Recur for remaining strings by

# 1. considering last characters

# of both strings

# 2. ignoring last character

# of first string

if (a[m - 1] == b[n - 1]):

return (count(a, b, m - 1, n - 1) +

NAME: H.T.NO: SUB.NAME:


count(a, b, m - 1, n))

else:

# If last characters are different,

# ignore last char of first string

# and recur for remaining string

return count(a, b, m - 1, n)

# Driver code

a = "GeeksforGeeks"

b = "Gks"

print(count(a, b, len(a),len(b)))

OUTPUT:
4

NAME: H.T.NO: SUB.NAME:


13. Higher order functions. Write a higher-order function count that counts

the number of elements in a list that satisfy a given test.

from functools import reduce

def getCount(listOfElems, cond = None):

'Returns the count of elements in list that satisfies the given condition'

if cond:

count = sum(cond(elem) for elem in listOfElems)

else:

count = len(listOfElems)

return count

def main():

# List of numbers

listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101]

print('**** Use map() & sum() to count elements in a list that satisfy

certain conditions****')

print('** Example 1 **')

# Count odd numbers in the list

count = sum(map(lambda x : x%2 == 1, listOfElems))

print('Count of odd numbers in a list : ', count)

print('** Example 1 : Explanation **')

# Get a map object by applying given lambda to each element in list

mapObj = map(lambda x : x%2 == 1, listOfElems)

NAME: H.T.NO: SUB.NAME:


print('Contents of map object : ', list(mapObj))

print('** Example 2**')

# Count even numbers in the list

count = sum(map(lambda x : x%2 == 0, listOfElems))

print('Count of even numbers in a list : ', count)

print('** Example 3**')

# count numbers in the list which are greater than 5

count = sum(map(lambda x : x>5, listOfElems))

print('Count of numbers in a list which are greater than 5: ', count)

print('**** Using sum() & Generator expression to count elements in list

based on conditions ****')

# count numbers in the list which are greater than 5

count = getCount(listOfElems, lambda x : x>5)

print('Count of numbers in a list which are greater than 5: ', count)

# count numbers in the list which are greater than 5 but less than 20

count = getCount(listOfElems, lambda x : x>5 and x < 20)

print('Count of numbers in a list which are greater than 5 but less than 20

: ', count)

# Get total number of elements in the list

count = getCount(listOfElems)

print('Total Number of elements in List: ', count)

print('**** Use List comprehension to count elements in list based on

conditions ****')

NAME: H.T.NO: SUB.NAME:


# count numbers in the list which are greater than 5

count = len([elem for elem in listOfElems if elem > 5])

print('Count of numbers in a list which are greater than 5: ', count)

print('**** Use reduce() function to count elements in list based on

conditions ****')

# count numbers in the list which are greater than 5

count = reduce(lambda default, elem: default + (elem > 5), listOfElems,

0)

print('Count of numbers in a list which are greater than 5: ', count)

if __name__ == '__main__':

main()

Output:

Count of numbers in a list which are greater than 5: <function count at

0x79b3217c93f0>

**** Use map() & sum() to count elements in a list that satisfy certain

conditions****

** Example 1 **

Count of odd numbers in a list : 6

** Example 1 : Explanation **

Contents of map object : [True, False, True, True, False, True, False, True,

True]

** Example 2**

Count of even numbers in a list : 3

NAME: H.T.NO: SUB.NAME:


** Example 3**

Count of numbers in a list which are greater than 5: 9

**** Using sum() & Generator expression to count elements in list based on

conditions ****

Count of numbers in a list which are greater than 5: None

Count of numbers in a list which are greater than 5 but less than 20 : None

Total Number of elements in List: 9

**** Use List comprehension to count elements in list based on conditions ****

Count of numbers in a list which are greater than 5: 9

**** Use reduce() function to count elements in list based on conditions ****

NAME: H.T.NO: SUB.NAME:


14. BRUTE FORCE SOLUTION TO THE KNAPSACK PROBLEM.

PROGRAM:

class ItemValue:
def __init__(self, wt, val, ind):
self.wt = wt
self.val = val
self.ind = ind
self.cost = val

def __lt__(self, other):


return self.cost < other.cost
# Greedy Approach

class FractionalKnapSack:
@staticmethod
def getMaxValue(wt, val, capacity):
iVal = []
for i in range(len(wt)):
iVal.append(ItemValue(wt[i], val[i], i))
# sorting items by value
iVal.sort(reverse=True)
totalValue = 0
for i in iVal:
curWt = int(i.wt)
curVal = int(i.val)
if capacity - curWt >= 0:
capacity -= curWt

NAME: H.T.NO: SUB.NAME:


totalValue += curVal
else:
fraction = capacity / curWt
totalValue += curVal * fraction
capacity = int(capacity - (curWt * fraction))
break
return totalValue

# Driver Code
if __name__ == "__main__":
wt = [10, 40, 20, 30]
val = [60, 40, 100, 120]
capacity = 50

# Function call
maxValue = FractionalKnapSack.getMaxValue(wt, val, capacity)
print("Maximum value in Knapsack =", maxValue)

OUTPUT:

Maximum value in Knapsack = 220.0

NAME: H.T.NO: SUB.NAME:


15.ASSUME THAT YOU ARE ORGANISING A PARTY FOR N PEOPLE
AND HAVE BEEN GIVEN A LIST L.

PROGRAM:

def findTheOrder(arr, s, N):


ans = []
A = [[] for i in range(N)]
for i in range(N):
A[i] = [arr[i], i + 1]
A = sorted(A)
q = []
index = 0
for i in range(2 * N):
if (s[i] == '0'):
ans.append(A[index][1])
q.append(A[index])
index += 1

else:
ans.append(q[-1][1])

del q[-1]
q = sorted(q)

# Print the values


for i in ans:
print(i, end = " ")

# Driver Code

NAME: H.T.NO: SUB.NAME:


if __name__ == '__main__':

# Given N
N=3
# Given arr[]
arr = [ 2, 1, 3 ]
# Given string
s = "001011"
# Function Call
findTheOrder(arr, s, N)

OUTPUT:

211332

NAME: H.T.NO: SUB.NAME:

You might also like