Ai Programs
Ai Programs
Output:
Program 3: Use Logic programming in Python to check for prime numbers.
def primechecker(num):
if num == 1:
print("Not a prime number")
elif num > 1:
prime = True
for i in range(2, num):
if num % i == 0:
print("Not a prime number")
prime = False
break
if prime:
print("Prime number")
else:
print("Not a prime number")
Output:
Program 4: Use logic programming in Python parse a family tree and infer
the relationships between the family members.
family_tree = {
"John": ["William", "David", "Adam"],
"William": ["Chris"],
"David": ["Wayne", "Tiffany", "Julie"],
# ... and so on
}
# Examples
print("Is John the grandparent of Wayne?", is_grandparent("John",
"Wayne"))
print("Are Chris and Julie siblings?", are_siblings("Chris",
"Julie"))
Output:
Program 5: Python Script for building a puzzle solver
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 all(num != board[row][i] for i in range(9)) \
and all(num != board[i][col] for i in range(9)) \
and all(num != board[row // 3 * 3 + i // 3][col //
3 * 3 + i % 3] for i in range(9)):
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0
return False
return True
puzzle = [
[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]
]
print("Original puzzle:")
for row in puzzle:
print(" ".join(map(str, row)))
print("\nSolving...")
if solve_sudoku(puzzle):
print("\nSolution:")
for row in puzzle:
print(" ".join(map(str, row)))
else:
print("No solution exists")
Output:
Program 6: Implementation of Naïve Bayes classifier, computing its accuracy and
visualizing its performance.
iris = load_iris()
X = iris.data
y = iris.target
nb_classifier = GaussianNB()
nb_classifier.fit(X_train, y_train)
y_pred = nb_classifier.predict(X_test)
plt.figure(figsize=(8, 6))
sns.heatmap(conf_mat, annot=True, cmap='Blues', fmt='d',
xticklabels=iris.target_names, yticklabels=iris.target_names)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show()
Output:
Program 7: Creation of a fuzzy control system which models how you might choose to
tip at a restaurant.
import numpy as np
def trimf(x, params):
a, b, c = params
result = np.zeros_like(x)
mask_ab = np.logical_and(a < x, x < b)
mask_bc = np.logical_and(b < x, x < c)
result[mask_ab] = (x[mask_ab] - a) / (b - a)
result[mask_bc] = (c - x[mask_bc]) / (c - b)
return np.maximum(0, np.minimum(result, 1))
service_quality_universe = np.arange(0, 11, 1)
food_quality_universe = np.arange(0, 11, 1)
tip_universe = np.arange(0, 26, 1)
service_quality_poor = trimf(service_quality_universe, [0, 0, 5])
service_quality_average = trimf(service_quality_universe, [0, 5, 10])
service_quality_good = trimf(service_quality_universe, [5, 10, 10])
# Defuzzify output
tip_output = defuzzify(aggregated_output_mf, tip_universe)
Output:
Program 8: Implementation of uninformed search techniques in python
class Graph:
def __init__(self, graph):
self.graph = graph
Output:
Program 9: Implementation of heuristic search techniques in python
import heapq
class Graph:
def __init__(self, graph):
self.graph = graph
while open_list:
_, current, path = heapq.heappop(open_list)
if current == goal:
return path
if current in closed_set:
continue
closed_set.add(current)
for neighbor, cost in self.graph[current].items():
if neighbor not in closed_set:
heapq.heappush(open_list, (len(path) + cost, neighbor,
path + [neighbor]))
return None
# Example graph
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'D': 3},
'C': {'A': 4, 'D': 2},
'D': {'B': 3, 'C': 2, 'E': 5},
'E': {'D': 5}
}
# Test A*
print("A*:", g.astar('A', 'E'))
Output:
Program 10: Python Script for Tokenizing Text Data
import re
def tokenize_text(text):
pattern = r'\b\w+\b'
return words
Output:
Program 11: Extracting the frequency of terms using a Bag of Words model.
# Example corpus
corpus = [
'This is the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?',
]
# Learn the vocabulary and transform the documents into a term-document matrix
bow_matrix = vectorizer.fit_transform(corpus)
Output:
Program 12: Predict the category to which a given piece of text belongs.
Output:
Program 13: Python code for visualizing audio speech signal
import pyaudio
import speech_recognition as sr
import numpy as np
import matplotlib.pyplot as plt
print("Recording...")
frames = []
for i in range(0, int(sample_rate / chunk_size * seconds)):
data = stream.read(chunk_size)
frames.append(data)
print("Recording finished.")
stream.stop_stream()
stream.close()
audio.terminate()
try:
text = recognizer.recognize_google(audio_source)
print("Transcription:", text)
except sr.UnknownValueError:
print("Speech Recognition could not understand audio.")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition
service; {0}".format(e))
if __name__ == "__main__":
# Record audio
audio_data = record_audio()
# Transcribe speech
transcribe_speech(audio_data, sample_rate=44100)
Output:
Program 14: Python code for Generating audio signals
import numpy as np
import scipy.io.wavfile as wav
# Parameters
duration = 3 # seconds
sampling_freq = 44100 # Hz
frequency = 440 # Hz (frequency of the sine wave)
Output:
sine_wave.wav
Program 15: Python code for synthesizing tones to generate music
import numpy as np
import sounddevice as sd
# Parameters
duration = 0.5 # seconds
sampling_freq = 44100 # Hz
notes_freq = {'C': 261.63, 'D': 293.66, 'E': 329.63, 'F': 349.23, 'G': 392.00,
'A': 440.00, 'B': 493.88}
melody_notes = "CDEFGABC"
melody = generate_melody(melody_notes, duration, sampling_freq)