Simple Python Code for AI Topics
This document contains simple Python examples for common Artificial
Intelligence (AI) topics including:
Search Algorithms
Knowledge Representation
Machine Learning Basics
Logic and Reasoning
Expert Systems
Neural Networks
Genetic Algorithms
Natural Language Processing
The examples are written in easy wording for beginners.
1. Search Algorithms
Search algorithms are used to find solutions or paths.
A. Linear Search
# Linear Search Example
numbers = [2, 4, 6, 8, 10]
key = 8
for i in range(len(numbers)):
if numbers[i] == key:
print("Element found at index", i)
break
Explanation:
Checks each element one by one.
Stops when the element is found.
B. Binary Search
# Binary Search Example
numbers = [1, 3, 5, 7, 9, 11]
key = 7
low = 0
high = len(numbers) - 1
while low <= high:
mid = (low + high) // 2
if numbers[mid] == key:
print("Element found at index", mid)
break
elif numbers[mid] < key:
low = mid + 1
else:
high = mid - 1
Explanation:
Works only on sorted lists.
Divides the list into halves.
C. Breadth First Search (BFS)
# BFS Example
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': [],
'F': []
}
queue = ['A']
visited = []
while queue:
node = [Link](0)
if node not in visited:
print(node)
[Link](node)
[Link](graph[node])
Explanation:
Visits nodes level by level.
Uses a queue.
D. Depth First Search (DFS)
# DFS Example
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': [],
'F': []
}
stack = ['A']
visited = []
while stack:
node = [Link]()
if node not in visited:
print(node)
[Link](node)
[Link](graph[node])
Explanation:
Goes deep into the graph first.
Uses a stack.
E. A* Search Algorithm
# Simple A* Example
from queue import PriorityQueue
graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 1)],
'C': [('D', 1)],
'D': []
}
heuristic = {
'A': 3,
'B': 1,
'C': 1,
'D': 0
}
pq = PriorityQueue()
[Link]((0, 'A'))
visited = []
while not [Link]():
cost, node = [Link]()
if node not in visited:
print(node)
[Link](node)
for neighbor, weight in graph[node]:
total_cost = cost + weight + heuristic[neighbor]
[Link]((total_cost, neighbor))
Explanation:
Uses path cost and heuristic value.
Commonly used in games and path finding.
2. Knowledge Representation
Knowledge representation stores information in a structured form.
A. Facts Using Dictionary
# Knowledge Representation using Dictionary
student = {
"name": "Ali",
"age": 21,
"course": "AI"
}
print(student["name"])
print(student["course"])
Explanation:
Stores facts as key-value pairs.
B. Semantic Network
# Simple Semantic Network
network = {
"Bird": "Can Fly",
"Fish": "Can Swim",
"Tiger": "Wild Animal"
}
print(network["Bird"])
Explanation:
Represents relationships between objects.
C. Frames
# Frame Representation
car = {
"brand": "Toyota",
"color": "White",
"model": 2024
}
for key, value in [Link]():
print(key, ":", value)
Explanation:
Frames store grouped information.
3. Logic and Reasoning
Logic helps AI systems make decisions.
A. Simple IF Rule
# Rule-Based Logic
temperature = 35
if temperature > 30:
print("Weather is Hot")
else:
print("Weather is Cool")
Explanation:
Uses rules to make decisions.
B. Expert System Example
# Simple Expert System
problem = input("Enter problem: ")
if problem == "slow internet":
print("Restart the router")
elif problem == "battery issue":
print("Charge the laptop")
else:
print("Problem not found")
Explanation:
Gives advice based on rules.
4. Machine Learning Basics
Machine learning helps computers learn from data.
A. Simple Prediction
# Simple Machine Learning Example
from sklearn.linear_model import LinearRegression
import numpy as np
x = [Link]([[1], [2], [3], [4]])
y = [Link]([2, 4, 6, 8])
model = LinearRegression()
[Link](x, y)
prediction = [Link]([[5]])
print("Prediction:", prediction)
Explanation:
Learns patterns from data.
Predicts future values.
B. Decision Tree
# Decision Tree Example
from sklearn import tree
features = [[25], [30], [45], [50]]
labels = [0, 0, 1, 1]
model = [Link]()
[Link](features, labels)
print([Link]([[40]]))
Explanation:
Makes decisions using conditions.
5. Neural Networks
Neural networks are inspired by the human brain.
# Simple Neural Network
from sklearn.neural_network import MLPClassifier
x = [[0, 0], [0, 1], [1, 0], [1, 1]]
y = [0, 1, 1, 0]
model = MLPClassifier(hidden_layer_sizes=(2,), max_iter=1000)
[Link](x, y)
print([Link]([[1, 0]]))
Explanation:
Learns patterns using neurons.
Used in image and speech recognition.
6. Genetic Algorithm
Genetic algorithms solve problems using natural selection ideas.
# Simple Genetic Algorithm
population = [2, 4, 6, 8]
fitness = []
for item in population:
[Link](item * 2)
print("Fitness values:", fitness)
Explanation:
Selects the best solutions.
Inspired by evolution.
7. Natural Language Processing (NLP)
NLP helps computers understand human language.
A. Tokenization
# Tokenization Example
text = "Artificial Intelligence is amazing"
words = [Link]()
print(words)
Explanation:
Splits text into words.
B. Sentiment Analysis
# Simple Sentiment Analysis
text = "This movie is good"
if "good" in text:
print("Positive Sentiment")
else:
print("Negative Sentiment")
Explanation:
Detects positive or negative text.
8. Robotics Example
# Simple Robot Movement
commands = ["left", "right", "forward"]
for command in commands:
print("Robot moves", command)
Explanation:
Simulates robot instructions.
9. Fuzzy Logic
Fuzzy logic handles uncertain values.
# Simple Fuzzy Logic Example
temperature = 28
if temperature > 25:
print("Temperature is Warm")
else:
print("Temperature is Cold")
Explanation:
Uses approximate reasoning.
10. Minimax Algorithm
Used in AI games like Tic Tac Toe.
# Simple Minimax Logic
scores = [3, 5, 2, 9]
best = max(scores)
print("Best score:", best)
Explanation:
Chooses the best possible move.
Conclusion
These examples cover basic AI concepts using simple Python code. They are
useful for:
Beginners learning AI
University assignments
Practice programs
Understanding AI fundamentals
Topics included:
Search Algorithms
Knowledge Representation
Logic and Reasoning
Machine Learning
Neural Networks
Genetic Algorithms
NLP
Robotics
Fuzzy Logic
Minimax Algorithm