0% found this document useful (0 votes)
2 views7 pages

Python Programs for AI and Data Science

The document contains multiple Python programs demonstrating various functionalities including creating and manipulating Pandas Series and DataFrames, visualizing data with plots, implementing the Alpha-Beta pruning algorithm, solving the 8-Queens problem, scheduling meetings, unifying terms in a knowledge base, and inferring new facts from existing ones. Each program showcases specific coding techniques and algorithms relevant to data science and artificial intelligence. Overall, it serves as a practical guide for implementing these concepts in Python.

Uploaded by

bslsdevi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Python Programs for AI and Data Science

The document contains multiple Python programs demonstrating various functionalities including creating and manipulating Pandas Series and DataFrames, visualizing data with plots, implementing the Alpha-Beta pruning algorithm, solving the 8-Queens problem, scheduling meetings, unifying terms in a knowledge base, and inferring new facts from existing ones. Each program showcases specific coding techniques and algorithms relevant to data science and artificial intelligence. Overall, it serves as a practical guide for implementing these concepts in Python.

Uploaded by

bslsdevi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

AI and Data Science Python Programs

01_pandas_series.py
import pandas as pd

# a) Pandas Series with labels


data = [Link]([10, 20, 30], index=['a', 'b', 'c'])
print("Series with labels:\n", data)

# b) Series from dictionary


dict_data = {'x': 100, 'y': 200, 'z': 300}
series_dict = [Link](dict_data)
print("\nSeries from dictionary:\n", series_dict)

# c) Creating a DataFrame
df = [Link]({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
print("\nData Frame:\n", df)

# d) Methods
print("\nDescribe:\n", [Link]())
print("\nHead:\n", [Link]())
print("\nTail:\n", [Link]())
print("\nInfo:")
[Link]()

02_pandas_visualization.py
import pandas as pd
import [Link] as plt

df = [Link]({
'A': [1, 2, 3, 4],
'B': [3, 7, 2, 5],
'C': [4, 1, 8, 6]
})

# i. Bar plot
[Link](kind='bar')
[Link]('Bar Plot')
[Link]()

# ii. Histogram
df['B'].plot(kind='hist')
[Link]('Histogram')
[Link]()
# iii. Line plot
[Link](kind='line')
[Link]('Line Plot')
[Link]()

# iv. Scatter plot


[Link](kind='scatter', x='A', y='C')
[Link]('Scatter Plot')
[Link]()

10_alpha_beta.py
def alpha_beta_pruning(node, depth, alpha, beta, maximizingPlayer,
values, tree):
if depth == 0 or node not in tree:
print(f"Leaf Node {node} with value {[Link](node, 0)}")
return [Link](node, 0)

if maximizingPlayer:
maxEval = float('-inf')
for child in tree[node]:
eval = alpha_beta_pruning(child, depth - 1, alpha, beta,
False, values, tree)
maxEval = max(maxEval, eval)
alpha = max(alpha, eval)
if beta <= alpha:
print(f"Pruned at node {child} (maximizing)")
break
print(f"Returning {maxEval} for node {node} (max)")
return maxEval
else:
minEval = float('inf')
for child in tree[node]:
eval = alpha_beta_pruning(child, depth - 1, alpha, beta,
True, values, tree)
minEval = min(minEval, eval)
beta = min(beta, eval)
if beta <= alpha:
print(f"Pruned at node {child} (minimizing)")
break
print(f"Returning {minEval} for node {node} (min)")
return minEval

tree = {
'A': ['B', 'C', 'D'],
'B': ['E', 'F'],
'C': ['G', 'H'],
'D': ['I', 'J']
}

values = {
'E': 3,
'F': 5,
'G': 6,
'H': 9,
'I': 1,
'J': 2
}

print("Alpha-Beta Pruning Result:")


result = alpha_beta_pruning('A', 3, float('-inf'), float('inf'), True,
values, tree)
print("\nOptimal Value:", result)

11_8_queens.py
N = 8

def print_solution(board):
for row in board:
print(" ".join("Q" if col else "." for col in row))
print()

def is_safe(board, row, col):


for i in range(row):
if board[i][col]:
return False
i, j = row - 1, col - 1
while i >= 0 and j >= 0:
if board[i][j]:
return False
i -= 1
j -= 1
i, j = row - 1, col + 1
while i >= 0 and j < N:
if board[i][j]:
return False
i -= 1
j += 1
return True

def solve_n_queens(board, row):


if row == N:
print_solution(board)
return True
res = False
for col in range(N):
if is_safe(board, row, col):
board[row][col] = 1
res = solve_n_queens(board, row + 1) or res
board[row][col] = 0
return res

board = [[0 for _ in range(N)] for _ in range(N)]


print("One solution to the 8-Queens Problem:\n")
solve_n_queens(board, 0)

12_default_scheduler.py
busy_slots = {
"Alice": [("Monday", "10AM"), ("Wednesday", "2PM")],
"Bob": [("Monday", "10AM"), ("Tuesday", "1PM")],
"Charlie": [("Wednesday", "2PM")],
"David": [("Friday", "11AM")],
"Eva": [("Tuesday", "1PM")]
}

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]


times = ["10AM", "11AM", "1PM", "2PM"]
places = ["Zoom", "Conference Room A", "Cafe"]

def schedule_meeting(busy_slots, days, times, places):


for day in days:
for time in times:
conflict = False
for person, busy in busy_slots.items():
if (day, time) in busy:
conflict = True
break
if not conflict:
place = places[0]
print("📅 Meeting Scheduled:")
print(f"Day : {day}")
print(f"Time : {time}")
print(f"Place : {place}")
return
print("⚠️ No common free slot found.")

schedule_meeting(busy_slots, days, times, places)


13_unification.py
def unify(x, y, substitutions=None):
if substitutions is None:
substitutions = {}
if x == y:
return substitutions
if is_variable(x):
return unify_var(x, y, substitutions)
if is_variable(y):
return unify_var(y, x, substitutions)
if isinstance(x, list) and isinstance(y, list) and len(x) == len(y):
for x1, y1 in zip(x, y):
substitutions = unify(x1, y1, substitutions)
if substitutions is None:
return None
return substitutions
return None

def unify_var(var, x, substitutions):


if var in substitutions:
return unify(substitutions[var], x, substitutions)
elif x in substitutions:
return unify(var, substitutions[x], substitutions)
else:
if occurs_check(var, x, substitutions):
return None
substitutions[var] = x
return substitutions

def is_variable(x):
return isinstance(x, str) and [Link]()

def occurs_check(var, x, substitutions):


if var == x:
return True
elif isinstance(x, list):
return any(occurs_check(var, xi, substitutions) for xi in x)
elif x in substitutions:
return occurs_check(var, substitutions[x], substitutions)
return False

x = ['likes', 'john', 'X']


y = ['likes', 'john', 'pizza']

print("Unifying:", x, "and", y)
subs = unify(x, y)
if subs:
print("Substitutions:", subs)
else:
print("Cannot be unified.")

14_knowledge_base.py
facts = [
"man(socrates)",
"man(plato)",
"man(aristotle)"
]

rules = [
{
"if": "man(X)",
"then": "mortal(X)"
}
]

def match(pattern, fact):


if "(" in pattern:
pred1, arg1 = [Link]("(")
arg1 = [Link](")")
pred2, arg2 = [Link]("(")
arg2 = [Link](")")
if pred1 != pred2:
return None
if [Link]():
return {arg1: arg2}
elif arg1 == arg2:
return {}
return None

def substitute(statement, subs):


if not subs:
return statement
pred, arg = [Link]("(")
arg = [Link](")")
if arg in subs:
return f"{pred}({subs[arg]})"
return statement

def infer(facts, rules):


inferred = set(facts)
new_inferred = True
while new_inferred:
new_inferred = False
for rule in rules:
for fact in list(inferred):
subs = match(rule["if"], fact)
if subs is not None:
new_fact = substitute(rule["then"], subs)
if new_fact not in inferred:
print(f"Inferred: {new_fact}")
[Link](new_fact)
new_inferred = True
return inferred

print("Initial Facts:", facts)


print("\nDerived Facts:")
inferred_facts = infer(facts, rules)

You might also like