ARTIFICIAL INTELLIGENCE LAB

==============================================================

PROGRAM 1: SIMPLE CALCULATOR & CALENDAR

AIM:
To implement a simple calculator and generate calendar using Python.

DESCRIPTION:
This program performs basic arithmetic operations like addition, subtraction, 
multiplication and division based on user input. It also uses Python's built-in 
calendar module to display the calendar for a given month and year.

PROGRAM:

# Simple Calculator
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter operator (+, -, *, /): ")

if op == '+':
    print("Result =", num1 + num2)
elif op == '-':
    print("Result =", num1 - num2)
elif op == '*':
    print("Result =", num1 * num2)
elif op == '/':
    if num2 != 0:
        print("Result =", num1 / num2)
    else:
        print("Division by zero not allowed")
else:
    print("Invalid operator")

# Calendar
import calendar
year = int(input("\nEnter year: "))
month = int(input("Enter month: "))
print(calendar.month(year, month))

OUTPUT:

Enter first number: 12
Enter second number: 4
Enter operator (+, -, *, /): *

Result = 48.0

Enter year: 2025
Enter month: 4

    April 2025
Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

==============================================================

PROGRAM 5: CONSTRAINT SATISFACTION PROBLEM (SUDOKU)

AIM:
To solve Sudoku using backtracking.

DESCRIPTION:
Sudoku is a constraint satisfaction problem where numbers must be placed 
in a 9x9 grid such that each row, column and 3x3 subgrid contains digits 
from 1 to 9 without repetition. This program uses backtracking to try 
possible values and ensures constraints are satisfied.


PROGRAM:

def print_board(board):
    for row in board:
        print(row)

def is_safe(board, row, col, num):
    for i in range(9):
        if board[row][i] == num or board[i][col] == num:
            return False

    start_row = row - row % 3
    start_col = col - col % 3

    for i in range(3):
        for j in range(3):
            if board[start_row+i][start_col+j] == num:
                return False
    return True

def solve_sudoku(board):
    for row in range(9):
        for col in range(9):
            if board[row][col] == 0:
                for num in range(1, 10):
                    if is_safe(board, row, col, num):
                        board[row][col] = num
                        if solve_sudoku(board):
                            return True
                        board[row][col] = 0
                return False
    return True

print("Enter Sudoku (9x9 matrix):")
board = []
for i in range(9):
    row = list(map(int, input().split()))
    board.append(row)

if solve_sudoku(board):
    print("\nSolved Sudoku:")
    print_board(board)
else:
    print("No solution exists")

OUTPUT:

Enter Sudoku (9x9 matrix):
5 3 0 0 7 0 0 0 0
6 0 0 1 9 5 0 0 0
0 9 8 0 0 0 0 6 0
8 0 0 0 6 0 0 0 3
4 0 0 8 0 3 0 0 1
7 0 0 0 2 0 0 0 6
0 6 0 0 0 0 2 8 0
0 0 0 4 1 9 0 0 5
0 0 0 0 8 0 0 7 9

Solved Sudoku:
[5, 3, 4, 6, 7, 8, 9, 1, 2]
[6, 7, 2, 1, 9, 5, 3, 4, 8]
[1, 9, 8, 3, 4, 2, 5, 6, 7]
[8, 5, 9, 7, 6, 1, 4, 2, 3]
[4, 2, 6, 8, 5, 3, 7, 9, 1]
[7, 1, 3, 9, 2, 4, 8, 5, 6]
[9, 6, 1, 5, 3, 7, 2, 8, 4]
[2, 8, 7, 4, 1, 9, 6, 3, 5]
[3, 4, 5, 2, 8, 6, 1, 7, 9]

==============================================================

PROGRAM 8: MCP NEURON (LOGIC GATES)

AIM:
To implement logic gates using MCP neuron.

DESCRIPTION:
The MCP (McCulloch-Pitts) neuron is a simple artificial neuron model that 
computes the weighted sum of inputs and compares it with a threshold to 
produce binary output. This program simulates AND, OR and NOT logic gates 
based on user input.

PROGRAM:

def mcp_neuron(inputs, weights, threshold):
    s = sum(i*w for i, w in zip(inputs, weights))
    return 1 if s >= threshold else 0

print("Choose Gate: AND / OR / NOT")
gate = input().upper()

if gate in ["AND", "OR"]:
    x1 = int(input("Enter first input: "))
    x2 = int(input("Enter second input: "))
    inputs = [x1, x2]

    if gate == "AND":
        result = mcp_neuron(inputs, [1,1], 2)
    else:
        result = mcp_neuron(inputs, [1,1], 1)

    print("Output:", result)

elif gate == "NOT":
    x = int(input("Enter input: "))
    result = mcp_neuron([x], [-1], 0)
    print("Output:", result)

OUTPUT:

Choose Gate: AND / OR / NOT
OR
Enter first input: 1
Enter second input: 0
Output: 1

==============================================================

PROGRAM 9: NLTK TEXT PROCESSING

AIM:
To perform tokenization, POS tagging and stopword removal.

DESCRIPTION:
Natural Language Toolkit (NLTK) is used for processing textual data. 
This program takes a sentence as input, splits it into tokens, identifies 
the grammatical parts of speech (POS) of each word, and removes common 
stopwords to obtain meaningful words.

PROGRAM:

import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk import pos_tag

nltk.download('punkt')
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger')

sentence = input("Enter a sentence: ")

words = word_tokenize(sentence)
print("\nTokens:", words)

print("\nPOS Tags:")
for w, t in pos_tag(words):
    print(w, "->", t)

filtered = [w for w in words if w.lower() not in stopwords.words('english')]
print("\nAfter removing stopwords:", filtered)

OUTPUT:

Enter a sentence: AI is very powerful

Tokens: ['AI', 'is', 'very', 'powerful']

POS Tags:
AI -> NNP
is -> VBZ
very -> RB
powerful -> JJ

After removing stopwords:
['AI', 'powerful']

==============================================================

PROGRAM 10: TOKENIZERS

AIM:
To implement word, sentence and paragraph tokenization.

DESCRIPTION:
Tokenization is the process of breaking text into smaller units such as 
words, sentences and paragraphs. This program uses NLTK to tokenize input 
text and also demonstrates paragraph splitting.

PROGRAM:

import nltk
from nltk.tokenize import word_tokenize, sent_tokenize

nltk.download('punkt')

text = input("Enter text: ")

print("\nWord Tokens:")
print(word_tokenize(text))

print("\nSentence Tokens:")
print(sent_tokenize(text))

print("\nParagraph Tokens:")
print(text.split("\\n\\n"))

OUTPUT:

Enter text: Hello! AI is amazing. NLP is fun.

Word Tokens:
['Hello', '!', 'AI', 'is', 'amazing', '.', 'NLP', 'is', 'fun', '.']

Sentence Tokens:
['Hello!', 'AI is amazing.', 'NLP is fun.']

Paragraph Tokens:
['Hello! AI is amazing. NLP is fun.']

==============================================================

PROGRAM 13: MAGIC SQUARE

AIM:
To generate odd and even magic squares.

DESCRIPTION:
A magic square is a square matrix where the sum of elements in each row, 
column and diagonal is equal. This program generates an odd order magic 
square using a standard algorithm where numbers are placed in a specific 
pattern.


PROGRAM:

def odd_magic_square(n):
    magic = [[0]*n for _ in range(n)]
    i, j = 0, n//2

    for num in range(1, n*n+1):
        magic[i][j] = num
        new_i, new_j = (i-1)%n, (j+1)%n

        if magic[new_i][new_j]:
            i = (i+1)%n
        else:
            i, j = new_i, new_j

    return magic

n = int(input("Enter odd number: "))
square = odd_magic_square(n)

print("\nMagic Square:")
for row in square:
    print(row)

OUTPUT:

Enter odd number: 3

Magic Square:
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]

==============================================================

==============================================================

PROGRAM 13: MAGIC SQUARE (ODD AND EVEN)

AIM:
To generate odd and even order magic squares.

DESCRIPTION:
A magic square is a square matrix in which the sum of elements in each row, 
column and both diagonals is the same. 

For odd order (n is odd), a standard algorithm (Siamese method) is used where 
numbers are placed diagonally upward.

For even order (n is even), a different method is used where numbers are filled 
sequentially and then replaced based on specific index conditions to satisfy 
the magic square property.

PROGRAM:

# Odd Magic Square
def odd_magic_square(n):
    magic = [[0]*n for _ in range(n)]
    i, j = 0, n//2

    for num in range(1, n*n+1):
        magic[i][j] = num
        new_i, new_j = (i-1)%n, (j+1)%n

        if magic[new_i][new_j]:
            i = (i+1)%n
        else:
            i, j = new_i, new_j

    return magic

# Even Magic Square
def even_magic_square(n):
    magic = [[(i*n) + j + 1 for j in range(n)] for i in range(n)]

    for i in range(n):
        for j in range(n):
            if (i % 4 == j % 4) or ((i % 4 + j % 4) == 3):
                magic[i][j] = n*n + 1 - magic[i][j]

    return magic


choice = input("Enter type (odd/even): ").lower()
n = int(input("Enter value of n: "))

if choice == "odd":
    square = odd_magic_square(n)
elif choice == "even":
    square = even_magic_square(n)
else:
    print("Invalid choice")
    square = []

if square:
    print("\nMagic Square:")
    for row in square:
        print(row)

OUTPUT:

Enter type (odd/even): even
Enter value of n: 4

Magic Square:
[16, 2, 3, 13]
[5, 11, 10, 8]
[9, 7, 6, 12]
[4, 14, 15, 1]

==============================================================