You are on page 1of 38

VIT Bhopal University

Kotrikalan village,
Sehore Dt.Bhopal-466144

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


ACADEMIC YEAR: 2021-2022

CSA2001-FOUNDAMENTALS IN AI and
ML LABORATORY

FALL SEMSTER

Submitted by- Sutikshan Sikarwar

Reg No-21BCE10601
INDEX

E.NO EXPERIMENT NAME Pg. No.


Study of facts, objects, predicates and variables in PROLOG.
1. 3-4

Study of Rules and Unification in PROLOG.


2. 5-6

Study of Rules and Unification in PROLOG.


3. 6

4. Study of arithmetic operators, simple input/output and compound goals 6-7


in PROLOG.
5. Study of recursion in PROLOG. 8-9
6. Study of Lists in PROLOG. 9-10
7. Study of dynamic database in PROLOG. 10-11
8. Study of string operations in PROLOG. Implement string operations like 11-17
substring, string position, palindrome etc.)
9. Write a prolog program to maintain family tree. 18-19
10. Write a prolog program to implement all set operations (Union, 20
intersection, complement etc.)
11. Write a prolog program to implement Library Management system. 20-25
12. Write a Program to Implement Breadth First Search using Python. 26-28
13. Write a Program to Implement Depth First Search using Python. 28-31
Write a Program to Implement Tic-Tac-Toe game using Python.
14. 31-35

15. Write a Program to Implement Travelling Salesman Problem using Python. 36-38
LAB PROGRAM CASE STUDY
1. Study of facts, objects, predicates and variables in PROLOG.
FACTS: -
A fact is a predicate expression that makes a declarative statement about the problem
domain. Whenever a variable occurs in a Prolog expression, it is assumed to
be universally quantified. Note that all Prolog sentences must end with a period.
likes(john, susie). /* John likes Susie */
likes(X, susie). /* Everyone likes Susie */
likes(john, Y). /* John likes everybody */
likes(john, Y), likes(Y, john). /* John likes everybody and everybody
likes John */
likes(john, susie); likes(john,mary). /* John likes Susie or John likes Mary
*/
not(likes(john,pizza)). /* John does not like pizza */
likes(john,susie) :- likes(john,mary)./* John likes Susie if John likes Mary.

OBJECTS: -

In Prolog Objects, an object is a named collection of predicate definitions. In this


sense an object is similar to a Prolog module. The object system can be seen as an
extension of SICStus Prolog's module system. In addition an object may have
attributes that are modifiable. Predicate definitions belonging to an object are
called methods. So, an object is conceptually a named collection of methods and
attributes. Some of the methods defined for an object need not be stored explicitly
within the object, but are rather shared with other objects by the inheritance
mechanism.

PREDICATES: -

There was a simple program that has five clauses. Head is a compound term for each first
three clauses with functor parent. It has two arguments with 2 arity.

1. parent(emma, robert).
2. parent(A, B) :- father(A, B).
3. parent(A, B) :- mother(A, B).
4. father(kevin, mary).
5. mother(anne, mary).

The following program includes the clauses for which functor parent is contained by the
head, but a different arity.

For example:

1. parent(kevin).
2. parent(A) :- son(A, B).
3. /* A is parent if A has a son B */

In the same program, we can also use a parent as an atom.

VARIABLES: -
Suppose we want to ask, "What course does Jeff teach"? This could be written as:
Is there a subject, X, which Jeff teaches?

Here, X, is a variable which stands for an object which the questioner does not know
about yet.

To answer the question, Prolog to find out the value of X, if it exists. As long as we do
not know the value of a variable it is said to be unbound or uninstantiated. When a
value is found, the variable is said to instantiated or bound to the value. The name of a
variable must begin with a capital letter or an underscore character, "_".

To ask Prolog to find the course which Jeff teaches, the following query is entered:
lectures(jeff, X)?
X = 611 output from Prolog

To ask which course(s) Ken teaches, a similar question may be asked,


lectures(ken , X)?
X = 621
X = 643

When there is more than one possible answer, Prolog will try to find all of them.
2. Study of Rules and Unification in PROLOG.
RULES
The previous question can be restated as a general rule:
One person, Teacher, teaches another person, Student if
X lectures in a subject, Subject and
Student studies Subject.

In Prolog this is written as:


teaches(Teacher, Student) :-
lectures(Teacher, Student),
studies(Student, Subject).

This is also called a clause. Facts are unit clauses and rules are non-unit clauses. ":-"
means "if" or "is implied by". This symbol is often called the neck symbol. The left
hand side of the neck is called the head. The right hand side of the neck is called
the body. The comma, ",", separating the goals is stands for and.

Try this rule out:


more_advanced(Student1, Student2) :-
year(Student1, Year1),
year(Student2, Year2),
Year1 > Year2.

Note the use of the predefined predicate ">".

Unification in Prolog
We will give a goal to evaluate and Prolog will work through the clauses in the database.
In this, Prolog attempts to match the goal with each clause. The matching process works
from left to right. The goal will fail if no match is found. If a match is found, the action will
take.

Prolog uses the unification technique, and it is a very general form of matching technique.
In unification, one or more variables being given value to make the two call terms
identical. This process is called binding the variables to values. For example, Prolog can
unify the terms cat(A), and cat(mary) by binding variable A to atom mary that means we
are giving the value mary to variable A. Prolog can unify person(Kevin, dane) and person(L,
S) by binding L and S to atom kevin and dane, respectively.

In starting, all variables have no value. In unification, once a variable bound to the value,
it can be made unbound again and then perhaps be bound to a new value using the
backtracking.

3. Study of “cut” and “fail” predicate in PROLOG.


a(X) :- b(X),!,c(X),fail.
a(X) :- d(X).

b(1).
b(4).
c(1).
c(3).

d(4).
The query a(X). produces

1 ?- a(X).
false.

2 ?-
but with this code

a(X) :- b(X),!,c(X).
a(X) :- d(X).

b(1).
b(4).
c(1).
c(3).

d(4).
The query a(X). results in :

1 ?- a(X).
X = 1.

4. Study of arithmetic operators, simple input/output and


compound goals in PROLOG.
Arithmetic Operations in Prolog
• Prolog arithmetic can be a little surprising ?- X = 3 + 4. X = 3+4 ;
• 3 + 4 is just a term whose functor is + and arguments are 3 and 4

A special predefined operator, is, is provided to circumvent this problem.


The is operator will force evaluation. So the right way to invoke arithmetic is: ?- X
is 3+4.
Now the answer will be:
X=7
The addition here was carried out by a special procedure that is associated with the
operator +.
We call such procedures built-in procedures

Input/Output: -
• A Prolog program can read data from input streams, and write data to output streams.

• Streams are associated with files.

• Data coming from the user's terminal is treated as just another input stream. Data output to the
terminal is treated as another output stream. Both of these "pseudo-files" are referred to by the
name user.

• The names of other files can be chosen by the programmer according to the rules of the OS.

COMPOUND GOALS: -

A compound goal is composed using operators similar to those employed by


PROLOG, that is, the comma for conjunction, the semicolon for disjunction, and the
arrow for conditional execution. Three of the several significant extensions to
PROLOG syntax and semantics are of particular interest here.
LAB CASE STUDY
5. Study of recursion in PROLOG.
Recursion is a technique in which one predicate uses itself (may be with some other
predicates) to find the truth value.
Let us understand this definition with the help of an example −
• is digesting(X,Y) :- just ate(X,Y).
• is digesting(X,Y) :-just ate(X,Z),is digesting(Z,Y).
So this predicate is recursive in nature. Suppose we say that just ate (deer, grass), it
means is digesting (deer, grass) is true. Now if we say is digesting (tiger, grass), this will
be true if is digesting(tiger, grass) :- just ate(tiger, deer), is digesting(deer, grass), then
the statement is digesting(tiger, grass) is also true.
There may be some other examples also, so let us see one family example. So if we
want to express the predecessor logic, that can be expressed using the following
diagram −
So, we can understand the predecessor relationship is recursive. We can express this
relationship using the following syntax −
• predecessor (X, Z): - parent (X, Z).
• predecessor (X, Z): - parent (X, Y), predecessor (Y, Z).

6. Study of Lists in PROLOG.


The list is a simple data structure that is widely used in non-numeric programming. List
consists of any number of items, for example, red, green, blue, white, dark. It will be
represented as, [red, green, blue, white, dark]. The list of elements will be enclosed
with square brackets.
A list can be either empty or non-empty. In the first case, the list is simply written as a
Prolog atom, []. In the second case, the list consists of two things as given below −
• The first item, called the head of the list;
• The remaining part of the list, called the tail.
Suppose we have a list like: [red, green, blue, white, dark]. Here the head is red and tail
is [green, blue, white, dark]. So, the tail is another list.
Now, let us consider we have a list, L = [a, b, c]. If we write Tail = [b, c] then we can also
write the list L as L = [ a | Tail]. Here the vertical bar (|) separates the head and tail parts.
So, the following list representations are also valid −
• [a, b, c] = [x | [b, c] ]
• [a, b, c] = [a, b | [c] ]
• [a, b, c] = [a, b, c | [ ] ]
For these properties we can define the list as −
A data structure that is either empty or consists of two parts − a head and a tail. The tail
itself has to be a list.

7. Study of dynamic database in PROLOG.

DYNAMIC DATABASE

Dynamic database can change dynamically at execution time and are of two types. Type1:
created at each execution. It grows, shrinks and is deleted at the end of program.

● This type of database is no longer available after program finishes its execution and is
called working memory.

Type2: Other type of dynamic databases are those which are stored in files and called
database files.

– These are consulted in any program whenever required.

– These types of databases are not part of any particular program and are available for
use in future by different programs using system defined predicates called save and
consult.

– While executing a Prolog program one can load database file(s) using 'consult'
predicate.

– These files can be updated dynamically at run time and saved using 'save' predicate.
● Clauses can be added to a database at run time using following predicates. asserta(X)
& assertz(X) - succeed by adding fact X in the beginning & at the end of database of
facts respectively.

● For example, asserta(father(mike, john)) adds fact father(mike, john) in the beginning
of current database.

● Clauses can be constructed dynamically and asserted in a dynamic database as follows:


start :- writeln('Input name of mother: '), readln(M), writeln('Input name of child: '),
readln(C), assert(parent(M, C)), assert(female(M)).

● Similarly obsolete clauses can be deleted by using system defined predicate called
retract from dynamic database at the run time.

● For example, retract(father(mike, X)) deletes the first fact father(mike, _) from working
memory.

● retractall(X) deletes all the clauses from a database whose head match with X.

● Example, retractall(father(X, Y)) deletes all the facts father( _ , _ ) and retractall( _ )
deletes all the clauses from the working memory.

8. Study of string operations in PROLOG.


Implement string operations like substring, string
position, palindrome etc.)
STRINGS
Strings are a time and space efficient mechanism to handle text in Prolog. Strings are
stores as a byte array on the global (term) stack and thus destroyed on backtracking and
reclaimed by the garbage collector.
Strings were added to SWI-Prolog based on an early draft of the ISO standard, offerring
a mechanism to represent temporary character data efficiently. As SWI-Prolog strings
can handle 0-bytes, they are frequently used through the foreign language interface for
storing arbitrary byte-sequences.
SWI-Prolog offers garbage collection on the atom-space as well as representing 0-bytes
in atoms. Although strings and atoms still have different features, new code should
consider using atoms to avoid too many representations for text as well as for
compatibility to other Prolog implementations. Below are some of the differences:
• creation
Creating strings is fast, as the data is simply copied to the global stack. Atoms are
unique and therefore more expensive in terms of memory and time to create. On the
other hand, if the same text has to be represented multiple times, atoms are more
efficient.
• destruction
Backtracking destroys strings at no cost. They are cheap to handle by the garbage
collector, but it should be noted that extensive use of strings will cause many garbage
collections. Atom garbage collection is generally faster.
String objects by default have no syntax and thus can only be created using the
predicates below or through the foreign language interface. There are two ways to make
read text into strings, both controlled through Prolog flags. One is by setting the
double_quotes flag to string and the other is by setting the backquoted_string flag to
true. In latter case, `Hello world` is read into a string and prints strings between
backquotes if quoted is true. This flag provides compatibility to LPA Prolog string
handling.
string_to_atom(?String, ?Atom)
Logical conversion between a string and an atom. At least one of the two arguments
must be instantiated. Atom can also be an integer or floating point number.
string_to_list(?String, ?List)
Logical conversion between a string and a list of ASCII characters. At least one of the
two arguments must be instantiated.
string_length(+String, -Length)
Unify Length with the number of characters in String. This predicate is functionally
equivalent to and also accepts atoms, integers and floats as its first argument.
string_concat(?String1, ?String2, ?String3)
if both String1 and String2 are unbound and String3 is bound to text, it breaks String3,
unifying the start with String1 and the end with String2 as append does with lists. Note
that this is not particularly fast on long strings as for each redo the system has to create
two entirely new strings, while the list equivalent only creates a single new list-cell and
moves some pointers around.
sub_string(+String, ?Start, ?Length, ?After, ?Sub)
Sub is a substring of String starting at Start, with length Length and String has After
characters left after the match.

Problem Statement:
Perform following String operations with and without pointers to arrays (without using the
library functions):
a. substring

b. palindrome

c. compare

d. copy

e. reverse.

Explanation:
For above statement "String operations with and without pointers to arrays without using
library function" we need to should know how exactly above operation works on string.
So for that we here implemented various operations on strings like substring, palindrome,
string comparisons, string copy, reverse the given string etc.

In first operation(substring), we took 2 strings and check whether string second is a


substring of first our not. If its a substring then here we checking the position of substring
in first string.

In second operation we check a sstring characters in such a manner that- first character
compared with last one, second with second last n so on.. you will understand when you
see code.

In third we just check two strings. we compare string character by character from left side.

In fourth, we just copy string characters of first string into second string which is easy to
understand when you see code for string copy.

In last, for string reverse used swapping method that swaps first and last character,
second n second last character and so on.

Program:

#include <stdio.h>

void substr(char str1[], char str2[]);


int palindrome(char str[]);
int compare(char str1[], char str2[]);
void copy(char str1[], char str2[]);
void reverse(char str[]);int main(){
char str1[100], str2[100];
int result, option;
do {
printf("\n1.Substring Searching");
printf("\n2.Check for Palindrome");
printf("\n3.String Comparison");
printf("\n4.Copy string");
printf("\n5.Reverse String");
printf("\n6.Quit");
printf("\n\nEnter Your Choice:");
scanf("%d", &option);switch (option) {
case 1:
printf("\nEnter 1st string:");
scanf("%s",&str1);
printf("\nEnter 2nd string:");
scanf("%s",&str2);
substr(str1, str2);
printf("\nPress a Character");
getch();
break;case 2:
printf("\n Enter a String:");
scanf("%s",&str1);
result = palindrome(str1);
if (result == 0)
printf("\nNot a palindrome");
else
printf("\nA palindrome");
printf("\nPress a Character");
getch();
break;
case 3:
printf("\nEnter 1st string:");
scanf("%s",&str1);
printf("\nEnter 2nd string:");
scanf("%s",&str2);
result = compare(str1, str2);
if (result == 0)
printf("\nboth are same");
else if (result > 0)
printf("\n1st>2nd");
else
printf("\n1st<2nd");
printf("\nPress a Character");
getch();
break;case 4:
printf("\nEnter a String:");
scanf("%s",&str1);
copy(str2, str1);
printf("\nResult=%s", str2);
printf("\nPress a Character");
getch();
break;
case 5:
printf("\nEnter a String:");scanf("%s",&str1);
reverse(str1);
printf("\nResult=%s", str1);
printf("\nPress a Character");
getch();
break;
default:
printf("\nInvalid Choice:");
break;
}
} while (option != 6);
return 0;
}

void substr(char str1[], char str2[]) {


int i, j, lena, lenb;
for (lena = 0; str1[lena] != '\0'; lena++);
for (lenb = 0; str2[lenb] != '\0'; lenb++);
for (i = 0; i <= lena - lenb + 1; i++) {
for (j = 0; str1[i + j] == str2[j] && str2[j] != '\0'; j++);
if (str2[j] == '\0')
printf("\nString found at location : %d", i + 1);
}
}

int palindrome(char str[]) {


int i, j;
i = j = 0;
while (str[j] != '\0')
j++;
while (i < j) {
if (str[i] != str[j - 1])
return (0);
i++;
j--;
}
return (1);
}

int compare(char str1[], char str2[]) {


int i;
i = 0;
while (str1[i] != '\0') {
if (str1[i] > str2[i])
return (1);
if (str1[i] < str2[i])
return (-1);
i++;
}
return (0);
}
void copy(char str2[], char str1[]) {
int i = 0;
while (str1[i] != '\0') {
str2[i] = str1[i];
i++;
}
str2[i] = '\0';
}

void reverse(char str[]) {


int i, j;
char temp;
i = j = 0;
while (str[j] != '\0')
j++;
j--;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}

Output:

1.Substring Searching
2.Check for Palindrome
3.String Comparison
4.Copy string
5.Reverse String
6.Quit

Enter Your Choice:1

Enter 1st string:Digvijay

Enter 2nd string:jay

String found at location : 6


Press a Character
1.Substring Searching
2.Check for Palindrome
3.String Comparison
4.Copy string
5.Reverse String
6.Quit

Enter Your Choice:2


Enter a String:racecar

A palindrome
Press a Character
1.Substring Searching
2.Check for Palindrome
3.String Comparison
4.Copy string
5.Reverse String
6.Quit

Enter Your Choice:3

Enter 1st string:sagar

Enter 2nd string:amar

1st>2nd
Press a Character
1.Substring Searching
2.Check for Palindrome
3.String Comparison
4.Copy string
5.Reverse String
6.Quit

Enter Your Choice:4

Enter a String:sasha

Result=sasha
Press a Character
1.Substring Searching
2.Check for Palindrome
3.String Comparison
4.Copy string
5.Reverse String
6.Quit

Enter Your Choice:5

Enter a String:race

Result=ecar
Press a Character

LAB program 3
Name – Tushar Kumar
Reg. no. – 21BCE11274
1. Write a prolog program to maintain family tree.
Input:-
Output:-
2. Write a prolog program to implement all set operations (Union, intersection, complement etc.)

Input:-

Output:-

3. Write a prolog program to implement Library Management system.


Input:-

// C program for the E-library


// Management System
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Create Structure of Library


struct library {
char book_name[20];
char author[20];
int pages;
float price;
};

// Driver Code
int main()
{
// Create a instance
struct library lib[100];

char ar_nm[30], bk_nm[30];

// Keep the track of the number of


// of books available in the library
int i, input, count;

i = input = count = 0;

// Iterate the loop


while (input != 5) {

printf("\n\n********######"
"WELCOME TO E-LIBRARY "
"#####********\n");
printf("\n\n1. Add book infor"
"mation\n2. Display "
"book information\n");
printf("3. List all books of "
"given author\n");
printf(
"4. List the count of book"
"s in the library\n");
printf("5. Exit");

// Enter the book details


printf("\n\nEnter one of "
"the above: ");
scanf("%d", &input);

// Process the input


switch (input) {

// Add book
case 1:

printf("Enter book name = ");


scanf("%s", lib[i].book_name);

printf("Enter author name = ");


scanf("%s", lib[i].author);

printf("Enter pages = ");


scanf("%d", &lib[i].pages);

printf("Enter price = ");


scanf("%f", &lib[i].price);
count++;

break;

// Print book information


case 2:
printf("you have entered"
" the following "
"information\n");
for (i = 0; i < count; i++) {

printf("book name = %s",


lib[i].book_name);

printf("\t author name = %s",


lib[i].author);

printf("\t pages = %d",


lib[i].pages);
printf("\t price = %f",
lib[i].price);
}
break;

// Take the author name as input


case 3:
printf("Enter author name : ");
scanf("%s", ar_nm);
for (i = 0; i < count; i++) {

if (strcmp(ar_nm,
lib[i].author)
== 0)
printf("%s %s %d %f",
lib[i].book_name,
lib[i].author,
lib[i].pages,
lib[i].price);
}
break;

// Print total count


case 4:
printf("\n No of books in "
"brary : %d",
count);
break;
case 5:
exit(0);
}
}
return 0;
}

Output:-

• Displaying the functoionalities and input for option 1:


• For Choice 2 and 3:
• For choice 4 and 5:
1. Write a Program to Implement Breadth First Search using
Python.

# Python3 Program to print BFS traversal


# from a given source vertex. BFS(int s)
# traverses vertices reachable from s.
from collections import defaultdict

# This class represents a directed graph


# using adjacency list representation
class Graph:

# Constructor
def init (self):

# default dictionary to store graph


self.graph = defaultdict(list)

# function to add an edge to graph


def addEdge(self,u,v):
self.graph[u].append(v)

# Function to print a BFS of graph


def BFS(self, s):

# Mark all the vertices as not visited


visited = [False] * (max(self.graph) + 1)

# Create a queue for BFS


queue = []

# Mark the source node as


# visited and enqueue it
queue.append(s)
visited[s] = True

while queue:

# Dequeue a vertex from


# queue and print it
s = queue.pop(0)
print (s, end = " ")

# Get all adjacent vertices of the


# dequeued vertex s. If a adjacent
# has not been visited, then mark it
# visited and enqueue it
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
# Driver code

# Create a graph given in


# the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)

print ("Following is Breadth First Traversal"


" (starting from vertex 2)")
g.BFS(2)

2. Write a Program to Implement Depth First Search using Python.


# Python3 program to print DFS traversal
# from a given given graph
from collections import defaultdict

# This class represents a directed graph using


# adjacency list representation
class Graph:

# Constructor
def init (self):

# default dictionary to store graph


self.graph = defaultdict(list)

# function to add an edge to graph


def addEdge(self, u, v):
self.graph[u].append(v)

# A function used by DFS


def DFSUtil(self, v, visited):

# Mark the current node as visited


# and print it
visited.add(v)
print(v, end=' ')

# Recur for all the vertices


# adjacent to this vertex
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)

# The function to do DFS traversal. It uses


# recursive DFSUtil()
def DFS(self, v):

# Create a set to store visited vertices


visited = set()

# Call the recursive helper function


# to print DFS traversal
self.DFSUtil(v, visited)

# Driver code

# Create a graph given


# in the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)

print("Following is DFS from (starting from vertex 2)")


g.DFS(2)

Lab Programs
3. Write a Program to Implement Tic-Tac-Toe game using
Python.
# Tic-Tac-Toe Program using
# random number in Python

# importing all necessary libraries


import numpy as np
import random
from time import sleep

# Creates an empty board


def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))

# Check for empty places on board


def possibilities(board):
l = []

for i in range(len(board)):
for j in range(len(board)):

if board[i][j] == 0:
l.append((i, j))
return(l)

# Select a random place for the player


def random_place(board, player):
selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)

# Checks whether the player has three


# of their marks in a horizontal row
def row_win(board, player):
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[x, y] != player:
win = False
continue

if win == True:
return(win)
return(win)

# Checks whether the player has three


# of their marks in a vertical row
def col_win(board, player):
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[y][x] != player:
win = False
continue

if win == True:
return(win)
return(win)

# Checks whether the player has three


# of their marks in a diagonal row
def diag_win(board, player):
win = True
y=0
for x in range(len(board)):
if board[x, x] != player:
win = False
if win:
return win
win = True
if win:
for x in range(len(board)):
y = len(board) - 1 - x
if board[x, y] != player:
win = False
return win

# Evaluates whether there is


# a winner or a tie
def evaluate(board):
winner = 0

for player in [1, 2]:


if (row_win(board, player) or
col_win(board,player) or
diag_win(board,player)):

winner = player

if np.all(board != 0) and winner == 0:


winner = -1
return winner

# Main function to start the game


def play_game():
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)

while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print("Board after " + str(counter) + " move")
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)

# Driver Code
print("Winner is: " + str(play_game()))
4. Write a Program to Implement Travelling
Salesman Problem using Python.
# Python3 program to implement traveling salesman
# problem using naive approach.
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
min_path = min(min_path, current_pathweight)

return min_path

# Driver Code
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))

You might also like