You are on page 1of 3

1)Aim: To create a python program for a simple calculator 3) Aim: To create a python program to generate Fibonacci series 5) Aim:

eries 5) Aim: To create a python program to count the special characters,


Algorithm:-1: Get input from the user (choice corresponding to Algorithm:1: Input the 'n' value until the Fibonacci series has been alphabets, digits, lowercase and uppercase characters(working eith
various operations like addition, subtraction, multiplication, generated:2: Initialize sum = 0, a = 0, b = 1 and count = 1 strings)
division):2: Get 2 integer inputs from the user:3: Perform the :3: while (count <= n), print sum:4: Increment the count variable:5: Algorithm:1: Start:2: Declare necessary files and variables:3: Read the
operations based on the user's choice:4: Print the output:5: Stop Swap a & b:6: sum = a + b:7: while(count > n), end algorithm:8: Else, input string:4: Count the no. of special characrters:5: Print the output:6:
Program:- repeat from steps 3 to 6 :9: Stop Stop
print("Operation: +, -, *, /") Program:- Program:-
select = input("Select operations: ") nterms = int(input("How many terms? ")) def Count(str):
n1, n2 = 0, 1 alpha, upper, lower, number, special = 0, 0, 0, 0, 0
num1 = float(input("Enter first number: ")) count = 0
num2 = float(input("Enter second number: ")) if nterms <= 0: for ch in str:
print("Please enter a positive integer") if ch.isalpha():
if select == "+": else: alpha += 1
print(num1, "+", num2, "=", num1 + num2) print("Fibonacci sequence:") if ch.isupper():
elif select == "-": while count < nterms: upper += 1
print(num1, "-", num2, "=", num1 - num2) print(n1) elif ch.islower():
elif select == "*": nth = n1 + n2 lower += 1
print(num1, "*", num2, "=", num1 * num2) n1 = n2 elif ch.isdigit():
elif select == "/": n2 = nth number += 1
print(num1, "/", num2, "=", num1 / num2) count += 1 elif ch != " ":
else: Output:- special += 1
print("INVALID INPUT") How many terms? 5 print('Digits: ', number)
Output:- Fibonacci sequence: print('Alphabets: ', alpha)
Operation: +, -, *, / 0 print('Special characters: ', special)
Select operations: + 1 print('Lowercase: ', lower)
Enter first number: 20 1 print('Uppercase: ', upper)
Enter second number: 30 2
20.0 + 30.0 = 50.0 3 str = input("Enter a string: ")
Count(str)
Output:- Enter a string: sathyabama @2023
Digits: 4
Alphabets: 10
Special characters: 1
Lowercase: 10
1 3 Uppercase: 0
5

7) Aim: To create a program for 9)Aim:-write a program to implement correlagon and regression. 11)Aim:-Implemengng clustering using k-means clustering algorithm
manipulagng the twiher dataset. Algorithm: 1.Import the libraries.:2.Read the csv file and let the Algorithm:1:import the all libraries:2:load the dataset file into a pandas.
Algorithm: variables (x,y).:3.Find the sum of the means (x,y).:4.Find zip-li, val, dataframe Using thread- csv funcgon:3: Create the instance of k-means
1.Import the required libraries (pandas, numpy). b&bo:5.Assign the test and train dataset split.:6.Create the machine class from the skleron cluster:4: Use the fit- predict() methed of the k-
2.Load the datset using pandas “read.csv” funcgon A store it in a Learning linear regression model using the train dataset. means object to cluster the customer based on their annual income and
variable (ds) “re”. 7.plorng classificagon data in matplotlib. spending scare and assign the resulgng duster labels to in variable y-
3.Get summary of the data using “data” , and remove the pahern in Program:- kmeans:5: Set appropriate labels for the plot and display it wing the
the dataset by declaring or using the det “remove pahern”. from sklearn.metrics import r2_score show' method of the netplotlib.pyplot medule
4.Replace the new “data” in the dataset available using [new] from sklearn.model_selection import train_test_split Program:-
5.Replace the text by using str replace () and print the data. import pandas as pd import numpy as np
6.Split the data and print to Henized tweet using “to henized” tweet import matplotlib.pyplot as plt import matplotlib.pyplot as plt
head() funcgon. df=pd.read_csv(r"Salary_Data.csv") import pandas as pd
7.Using import porter stemmer remove the common & inflexional x=list(df["YearsExperience"])
endings from words in English and print the tokenized tweet. y=list(df["Salary"]) df = pd.read_csv('Mall_Customers.csv')
df df.head(3)
Program:- import pandas as pd
import numpy as np
len(df)
import re def LinearRegressor(x,y):
sumX=sum(x)
X = df.iloc[:, [3, 4]].values
data = pd.read_csv('tweets1.csv') sumY=sum(y)
X[0:5]
data xMean=sumX/len(x)
yMean=sumY/len(y) from sklearn.cluster import KMeans
def remove_pattern(input_txt, pattern): x_minus_xmean=[val-xMean for val in x] kmeans = KMeans(n_clusters = 5, init = 'k-
r = re.findall(pattern, input_txt) y_minus_ymean=[val-yMean for val in y] means++', max_iter = 300, n_init = 10,
for i in r: zip_li=zip(x_minus_xmean,y_minus_ymean) random_state = 0)
input_txt = re.sub(i, '', input_txt) val=[x*y for x,y in zip_li] kmeans.n_clusters
return input_txt b1=sum(val)/sum([x**2 for x in x_minus_xmean])
print(data) b0=yMean-b1*xMean y_kmeans = kmeans.fit_predict(X)
return b0,b1
data['new'] = np.vectorize(remove_pattern)(data['text'], "@[\w]*") x_train, x_test, y_train, y_test = train_test_split(x, y, df['cluster'] = y_kmeans
print(data) test_size=1/2,shuffle=True) print(y_kmeans.shape)
b=LinearRegressor(x_train,y_train)
y_pred=[b[0]+b[1]*val for val in x_test]

r2_score(y_test,y_pred)
7 9 11
6) Aim:- Data processing building good training set. 4) Aim: To create a python program to import functions as modules 2)Aim: To create a python program to generate armstrong numbers
Alogrithm:1: Start:2:Import panda:3: Describe and get informagon Algorithm:1: Start:2: Create example module script files:3: Define Algorithm:1: Take the numbers as input from the user:2: Determine
about data:4: Find the values of x and y:5:Print the output:6:Stop the relevant functions:4: Create main script files:5: Declare necessary the number of digits, say it is n:3: Extract each digit from the
Program. variables:6: Import example module file:7: Print the output:8: Stop number using a loop. Now raise each of these digits to the power
Program:- Program:- n:4: Keep adding the nth power of these digits in a variable, say
import pandas as pd def summation(a, b): sum:5: Once the sum of all the nth power of the digits is obtained,
df = pd.read_csv('Heart.csv') return a + b the loop terminates. If both are equal, then it is an armstrong
df def multiplication(a, b): number and is printed
return a * b Program:-
df.describe() def division(a, b): lower = int(input("Enter the lower range: "))
return a / b upper = int(input("Enter the upper range: "))
df.info() a = int(input("Enter the first number: ")) for num in range(lower, upper + 1):
b = int(input("Enter the second number: ")) order = len(str(num))
df.replace(0, 'NAN') print("Sum = ", summation(a, b)) sum = 0
print("Product = ", multiplication(a, b)) temp = num
df.dropna() print("Divisor = ", division(a, b)) while temp > 0:
output:- digit = temp % 10
df.fillna(df.mean()) Enter the first number: 5 sum += digit ** order
Enter the second number: 10 temp //= 10
x = df.iloc[:, 0:14].values Sum = 15 if num == sum:
x Product = 50 print(num)
Divisor = 0.5 Output:-
y = df.iloc[:, 14].values Enter the lower range: 100
y Enter the upper range: 500
153
from sklearn.model_selection import train_test_split 370
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, 371
random_state = 0) 407
print(x_train.shape)
print(x_test.shape)

6 4 2

10) Write program to implement classificagon Algorithm by using 8) Aim:-to evaluate the result of machine learning or confusion
python. matrix.
Algorithm:1.Import the libraries:2.Fetch data.:3.Determine the target Algorithm:1:Read actual values vs predicted values:2: compute the
variable.:4.creagon of predictors variables.:5.test and train dataset following:3:compute the confusion matrix:4: compute the accuracy
split.:6.create the machine learning classificagon model using the train :5:compute the specificity:6:compute the Sensigvity:7:compute the
dataset.:7.The classificagon model accuracy score in python. precision:8: compute the recall:9: compute the misclassificagon
8.Predicgon.:9.Plorng classificagon data in matplotlib. error.
Program:- import pandas as pd Program:-
data=pd.read_csv("Iris.csv") y=['0','1','0','1','1','1','0','1','0','1',
data '0','0','0','1','1','1','0','1','1','0']
y_pred = ['0','0','0','0','1','0','1','1','1','1'
X =data.iloc[:,[1,2,3,4]].values ,'0','0','0','0','0','1','0','1','1','0']
y =data.iloc[:,5].values print (y)

from sklearn.model_selection import print(y_pred)


train_test_split
X_train, X_test, y_train, y_test =
train_test_split(X, y, test_size=0.2, j=0
random_state=1) TP, TN, FP, FN = 0, 0, 0, 0
for i in y:
from sklearn.naive_bayes import GaussianNB if i == '1' and y_pred[j] == '1':
gnb = GaussianNB() TP += 1
gnb.fit(X_train, y_train) elif i == '0' and y_pred[j] == '0':
y_pred=gnb.predict(X_test) TN += 1
elif i == '1' and y_pred[j] == '0':
from sklearn import metrics FP += 1
print("Classification Accuracy:", elif i == '0' and y_pred[j] == '1':
metrics.accuracy_score(y_test, y_pred)*100) FN += 1
cm=metrics.confusion_matrix(y_test,y_pred) j += 1
cm confusion_matrix = [TP, TN, FP, FN]
print ("Confusion Matrix : ", confusion_matrix)
import seaborn as sn ACC = (TP + TN) / (TP + FP + TN + FN)
from matplotlib import pyplot as plt
print ("ACCURACY : ", ACC)
plt.figure(figsize=(5,4))
PREC = TP / (TP + FP)
sn.heatmap(cm,annot=True)
plt.xlabel('Predicted value') print ("PRECISION : ", PREC)
plt.ylabel('Actual value') REC = TP / (TP + FN)
plt.show() print ("RECALL : ", REC) 8
10

You might also like