Python Code Snippets for Data Science and AI
# **Program 1:
NumPy
Array Operations**
import numpy as np
arr=np.Array([[1,2,3],[4,5,6],[7,8,9]])
print(“Sum of all columns:”,np.
sum(arr,axis=0))
print(“Product of all rows:”,np.Prod(arr,axis=1))
print(“Last two rows and columns:\n”,arr[1:,1:])
arr2=np.Array([[9,8,7],[6,5,4],[3,2,1]])
print(“Element-wise addition:\n”,arr+arr2)
.
.
# **Program 2: Vowel Frequency in Each Word**
sentence=input(“Enter a sentence in lowercase: “)
vowels=’aeiou’
for w in sentence.Split():
print(f”{w}: {sum(w.Count(v) for v in vowels)}”)
.
.
# **Program 3: Palindrome Checker**
s=input(“Enter a string: “)
if s==s[::-1]:
print(“Palindrome!”);print((s+” “)*len(s))
else:print(“Not a palindrome.”)
.
.
# **Program 4: Random Integers Divisible by 5 (Mean, Median, Mode)**
import random,statistics
nums=[random.Randint(100,999)//5*5 for _ in range(3)]
print(“Numbers:”,nums)
print(“Mean:”,statistics.Mean(nums))
print(“Median:”,statistics.Median(nums))
print(“Mode:”,statistics.Mode(nums))
.
.
# **Program 5: Recursive Functions (Sum, Reverse, Binary)**
def sum_digits(n):
return 0 if n==0 else n%10+sum_digits(n//10)
def reverse_num(n,rev=0):return rev if n==0 else reverse_num(n//10,rev*10+n%10)
def binary(n):return ” if n==0 else binary(n//2)+str(n%2)
num=int(input(“Enter a number: “))
print(“Sum of digits:”,sum_digits(num))
print(“Reverse:”,reverse_num(num))
print(“Binary:”,binary(num))
.
.
# **Program 6: Dictionary of Months and Days**
months={‘January’:31,’February’:28,’March’:31,’April’:30,’May’:31,’June’:30,’July’:31,’August’:31,’September’:30,’October’:31,’November’:30,’December’:31}
print(months)
.
.
# **Program 7: NumPy Indices of Max & Min Values**
import numpy as np
arr=np.Array([[10,50,30],[60,20,40]])
print(“Max indices:”,np.Argmax(arr,axis=1))
print(“Min indices:”,np.Argmin(arr,axis=1))
.
.
# **Program 8: NumPy 2D Array Info (Shape, Type, Dtype)**
arr=np.Array([[1,2,3],[4,5,6]],dtype=np.Int32)
print(“Array:\n”,arr)
print(“Shape:”,arr.Shape)
print(“Type:”,type(arr))
print(“Data Type:”,arr.Dtype)
.
.
# **Program 9: 5×5 Matrix Row Sum**
arr=np.Zeros((5,5))
for i in range(5):arr[i]=np.Arange(5)
print(“Matrix:\n”,arr)
print(“Row sums:”,np.Sum(arr,axis=1))
.
.
# **Program 10:
Matplotlib
Graphs and Charts**
import matplotlib.Pyplot as plt, numpy as np
x=np.Arange(1,6);y=x*2
plt.Plot(x,y);plt.Title(“Line Chart”);plt.Xlabel(“X Axis”);plt.Ylabel(“Y Axis”);plt.Grid(True);plt.Show()
plt.Plot(x,x**2,label=’x^2′,linestyle=’–‘);plt.Plot(x,x**3,label=’x^3′,linestyle=’:’);plt.Legend();plt.Show()
data=np.Random.Randint(1,50,20)
plt.Scatter(range(len(data)),data,color=’red’,marker=’*’,s=100);plt.Show()
plt.Bar(range(len(data)),data);plt.Show()
plt.Hist(data,bins=10,color=’green’);plt.Show()
labels=[‘Food’,’Rent’,’Travel’,’Entertainment’];sizes=[30,40,20,10]
plt.Pie(sizes,labels=labels,autopct=’%1.1f%%’);plt.Title(“Expense Distribution”);plt.Show()
.
.
# **Program 11: Graph DFS and BFS Traversal**
from collections import deque
graph={‘A’:[‘B’,’C’],’B’:[‘D’,’E’],’C’:[‘F’],’D’:[],’E’:[‘F’],’F’:[]}
def dfs(n,v=set()):
if n not in v:
print(n,end=’ ‘);v.Add(n)
for x in graph[n]:dfs(x,v)
def bfs(s):
v=set();q=deque([s])
while q:
n=q.Popleft()
if n not in v:
print(n,end=’ ‘);v.Add(n);q.Extend(graph[n])
print(“DFS:”,end=’ ‘);dfs(‘A’);print(“\nBFS:”,end=’ ‘);bfs(‘A’)
.
.
# **Program 12: Hill Climbing Algorithm**
import random
def hill_climb():
c=random.Randint(0,100)
while True:
n=c+random.Choice([-1,1])
if n<0 or n>100:break
if n**2>c**2:c=n
else:break
return c
print(“Best solution found:”,hill_climb())
.
.
# **Program 13: Simple Reflex Agent – Traffic Light**
def traffic_light_agent(l):
if l==”red”:return”Stop”
elif l==”yellow”:return”Slow down”
elif l==”green”:return”Go”
else:return”Invalid”
print(traffic_light_agent(input(“Enter light color: “).Lower()))
.
.
# **Program 14: Simple Reflex Agent – Vacuum Cleaner**
def vacuum_agent(s):return”Clean the room” if s==”dirty” else”Move to next room”
print(vacuum_agent(input(“Enter room status (clean/dirty): “).Lower()))
.
.
# **Program 15: Model-Based Agent – Traffic Light**
state={“previous_light”:None}
def model_based_traffic_agent(l):
if state[“previous_light”]==”green”and l==”yellow”:a=”Prepare to stop”
elif l==”red”:a=”Stop”
else:a=”Go”
state[“previous_light”]=l
return a
print(model_based_traffic_agent(“green”))
print(model_based_traffic_agent(“yellow”))
.
.
# **Program 16: Model-Based Agent – Weather Forecast**
state={“previous”:None}
def weather_agent(c):
if c==”rainy”:a=”Carry umbrella”
elif c==”sunny”:a=”Wear sunglasses”
else:a=”Normal day”
state[“previous”]=c
return a
print(weather_agent(“sunny”))
print(weather_agent(“rainy”))
.
.
# **Program 17: Iris Dataset Analysis**
import pandas as pd,matplotlib.Pyplot as plt
df=pd.Read_csv(“iris.Csv”)
print(“Samples:”,df.Shape[0]);print(“Attributes:”,df.Shape[1])
print(df.Head(20));print(df.Tail(20));print(df.Iloc[40:60])
print(df.Describe());print(“Mode:\n”,df.Mode())
print(“Species count:\n”,df[‘species’].Value_counts())
df[‘species’].Value_counts().Plot(kind=’bar’,title=”Species Count”);plt.Show()
df[“SepalArea”]=df[“sepal_length”]*df[“sepal_width”]
df[“PetalArea”]=df[“petal_length”]*df[“petal_width”]
df.Plot.Scatter(x=”SepalArea”,y=”PetalArea”,legend=True);plt.Legend(loc=’upper left’);plt.Show()
df[“SepalArea”].Plot(kind=’hist’,alpha=0.5);df[“PetalArea”].Plot(kind=’hist’,alpha=0.5)
plt.Legend([“SepalArea”,”PetalArea”],loc=’upper left’);plt.Show()
.
.
# **Program 18: Titanic Dataset Analysis**
import pandas as pd,seaborn as sns,matplotlib.Pyplot as plt
df=pd.Read_csv(“titanic.Csv”)
print(df.Isnull().Sum())
df[‘has_Cabin’]=df[‘Cabin’].Apply(lambda x:0 if pd.Isnull(x)else 1)
df.Drop(‘Cabin’,axis=1,inplace=True)
df[‘Age’].Fillna(df[‘Age’].Median(),inplace=True)
df[‘Embarked’].Fillna(df[‘Embarked’].Mode()[0],inplace=True)
for i,c in enumerate(df.Select_dtypes(include=’object’).Columns):
plt.Figure(i);sns.Countplot(x=c,data=df);plt.Title(f”Count Plot of {c}”);plt.Show()
