DEPARTMENT OF COMPUTER SCIENCE
SCHOOL OF COMPUTER SCIENCE AND ENGINEERING
BHARATHIAR UNIVERSITY
COIMBATORE – 641 046
NAME OF THE CANDIDATE :
REGISTER NUMBER :
M.Sc. DATA SCIENCE
SEMESTER - I
PYTHON AND R PROGRAMMING LAB
24DS1C5
NOVEMBER 2024
DEPARTMENT OF COMPUTER SCIENCE
SCHOOL OF COMPUTER SCIENCE AND ENGINEERING
BHARATHIAR UNIVERSITY
COIMBATORE – 641 046
CERTIFICATE
This is to certify that the bonafide record work PYTHON AND R PROGRAMMING LAB –
24DS1C5 was done and submitted by Mr. / Ms. with the Register Number
in partial fulfillment of the requirements for the Degree, Master of Science in
Data Science at the Department of Computer Science, Bharathiar University, Coimbatore – 641
046, during November 2024.
Submitted for Practical Examination on
Staff-In-Charge Head of the Department
Internal Examiner External Examiner
INDEX
S.NO DATE TITLE PAGE NO SIGNATURE
PYTHON PROGRAMMING
1 Swapping of values
2 Conversion of ASCII to binary
3 Printing the first n row of Pascal's triangle.
Calculation of upper case and lower-case
4
letters in a string
5 Programs using Tuple
6 Programs using conditionals
7 Programs using dictionaries
8 Programs using Boolean operators
9 Implementation of functions
10 Programs using NumPy
11 Programs using Pandas
12 Implementation of Maclaurin series
13 Programs using seaborn
14 Programs using Matplotlib
R PROGRAMMING
15 Vector manipulations
16 Matrix operations
17 Array Operations
18 Operations using data frame
19 Implementation of functions
Drawing scatter plot, box plot, violin plot,
20
dot plot, bar plot, line plot
21 Geometric Shapes
22 Data transformations
23 Finding missing values
1.Swapping of values
To swap the values of two variables and display the result.
print("SWAP THE VALUES")
a = 100
b = 50
print("a =", a)
print("b =", b)
a, b = b, a
print("The value of a =", a)
print("The value of b =", b)
OUTPUT
2. Conversion of ASCII to binary
To convert an ASCII character to its binary equivalent and display the result.
print("ASCII TO BINARY")
x = input("Enter a Character: ")
y = ord(x)
print("The ASCII value of the given character is", y)
print("The Binary value of ASCII is", bin(y))
OUTPUT
3. Printing the first n row of Pascal's triangle.
To print the first `n` rows of Pascal's Triangle.
def print_pascals_triangle(n):
for i in range(n):
row = [1]
if i > 0:
for j in range(1, i):
row.append(prev_row[j-1] + prev_row[j])
row.append(1)
print(" " * (n - i), end="")
print(" ".join(map(str, row)))
prev_row = row
rows = int(input("Enter the number of rows: "))
print_pascals_triangle(rows)
OUTPUT
4. Calculation of upper case and lower-case letters in a string
To calculate the number of uppercase and lowercase letter in a given string.
def count_case(s):
upper_count = sum(1 for char in s if char.isupper())
lower_count = sum(1 for char in s if char.islower())
print("Number of uppercase letters:", upper_count)
print("Number of lowercase letters:", lower_count)
input_string = input("Enter a string: ")
count_case(input_string)
OUTPUT
5. Programs using Tuple
Perform the following operations using the given tuple.
('F', 'l', 'a', 'b', 'b', 'e', 'r', 'g', 'a', 's', 't', 'e', 'd')
• Add an ! at the end of the tuple
• Convert a tuple to a string
• Extract ('b', 'b') from the tuple
• Find out number of occurrences of 'e' in the tuple
• Check whether 'r' exists in the tuple
• Convert the tuple to a list
• Delete characters 'b, 'b', 'e', 'r' from the tuple
tup = ('F', 'l', 'a', 'b', 'b', 'e', 'r', 'g', 'a', 's', 't', 'e', 'd')
tup = tup + ('!',)
print("Tuple after adding '!' at the end:", tup)
string_representation = ''.join(tup)
print("String representation of the tuple:", string_representation)
extracted = tup[3:5]
print("Extracted ('b', 'b') from the tuple:", extracted)
e_count = tup.count('e')
print("Number of occurrences of 'e' in the tuple:", e_count)
exists_r = 'r' in tup
print("Does 'r' exist in the tuple?", exists_r)
list_representation = list(tup)
print("List representation of the tuple:", list_representation)
tup = tuple(char for char in tup if char not in ('b', 'e', 'r'))
print("Tuple after deleting 'b', 'b', 'e', 'r':", tup)
OUTPUT
6. Programs using conditionals
To demonstrate the use of conditionals in Python by evaluating different conditions.
number = int(input("Enter a number: "))
# Check if the number is positive, negative, or zero
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
# Check if the number is even or odd
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
OUTPUT
7. Programs using dictionaries
To create three dictionaries and concatenate them to create a fourth dictionary.
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'e': 5, 'f': 6}
dict4 = {**dict1, **dict2, **dict3}
print("Concatenated Dictionary:", dict4)
OUTPUT
8. Programs using Boolean operators
To demonstrate the use of Boolean operators (`and`, `or`, `not`) in Python.
x = True
y = False
result_and = x and y
result_or = x or y
result_not_x = not x
print("Result of x and y:", result_and)
print("Result of x or y:", result_or)
print("Result of not x:", result_not_x)
OUTPUT
9. Implementation of functions
A) Sum and Product of Three Integers
def calculate_sum_and_product(a, b, c):
total = a + b + c
product = a * b * c
return total, product
num1 = int(input("Enter first integer: "))
num2 = int(input("Enter second integer: "))
num3 = int(input("Enter third integer: "))
sum_result, product_result = calculate_sum_and_product(num1, num2, num3)
print("Sum:", sum_result)
print("Product:", product_result)
OUTPUT
B) Compute n + nn + nnn + nnnn
def compute(n):
result = n + (n * 11) + (n * 111) + (n * 1111)
return result
digit = input("Enter a single digit: ")
result = compute(int(digit))
print("Result:", result)
OUTPUT
10. Programs using NumPy
To find the number of elements of a NumPy array, the length of one array element in bytes,
and the total bytes consumed by the elements.
import numpy as np
array = np.array([1, 2, 3, 4, 5])
num_elements = array.size
element_size = array.itemsize
total_bytes = array.nbytes
print("Number of elements in the array:", num_elements)
print("Length of one array element in bytes:", element_size)
print("Total bytes consumed by the elements:", total_bytes)
OUTPUT
11. Programs using Pandas
To add, subtract, multiply, and divide two Pandas Series.
import pandas as pd
series1 = pd.Series([10, 20, 30, 40])
series2 = pd.Series([1, 2, 3, 4])
addition = series1 + series2
subtraction = series1 - series2
multiplication = series1 * series2
division = series1 / series2
print("Series 1:")
print(series1)
print("\nSeries 2:")
print(series2)
print("\nAddition:")
print(addition)
print("\nSubtraction:")
print(subtraction)
print("\nMultiplication:")
print(multiplication)
print("\nDivision:")
print(division)
OUTPUT
12. Implementation of Maclaurin series
To calculate the sine of an angle using the Maclaurin series expansion.
import math
def maclaurin_sine(x):
sine_approx = 0
for n in range(5):
sine_approx += ((-1)**n * (x**(2*n + 1))) / math.factorial(2*n + 1)
return sine_approx
angle = float(input("Enter the angle in radians: "))
result = maclaurin_sine(angle)
print("Maclaurin series approximation of sin({}) is: {}".format(angle, result))
OUTPUT
13. Programs using seaborn
To demonstrate how to create a simple scatter plot using Seaborn.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="day")
plt.title("Scatter Plot of Total Bill vs Tip")
plt.xlabel("Total Bill ($)")
plt.ylabel("Tip ($)")
plt.show()
OUTPUT
14. Programs using Matplotlib
To draw a line from position (0, 0) to position (6, 250) using Matplotlib.
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.title("Line from (0, 0) to (6, 250)")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
OUTPUT
15. Vector manipulations
To demonstrate various vector manipulations in R, including creating a vector, accessing
elements, and performing operations.
vector <- c(10, 20, 30, 40, 50)
first_element <- vector[1]
last_element <- vector[length(vector)]
sum_vector <- sum(vector)
mean_vector <- mean(vector)
max_vector <- max(vector)
min_vector <- min(vector)
print(paste("First element:", first_element))
print(paste("Last element:", last_element))
print(paste("Sum of vector:", sum_vector))
print(paste("Mean of vector:", mean_vector))
print(paste("Max of vector:", max_vector))
print(paste("Min of vector:", min_vector))
OUTPUT
16. Matrix operations
To demonstrate various matrix operations in R, including creating a matrix, accessing
elements, and performing basic operations.
matrix1 <- matrix(1:9, nrow=3, ncol=3)
matrix2 <- matrix(9:1, nrow=3, ncol=3)
element <- matrix1[2, 3]
matrix_sum <- matrix1 + matrix2
matrix_product <- matrix1 %*% matrix2
matrix_transpose <- t(matrix1)
print("Matrix 1:")
print(matrix1)
print("Matrix 2:")
print(matrix2)
print(paste("Element at row 2, column 3:", element))
print("Sum of matrices:")
print(matrix_sum)
print("Product of matrices:")
print(matrix_product)
print("Transpose of Matrix 1:")
print(matrix_transpose)
OUTPUT
17. Array Operations
To demonstrate basic array operations in R, including creating an array, accessing elements,
and performing operations.
array1 <- array(1:12, dim = c(3, 4))
element <- array1[2, 3]
array_sum <- array1 + 5
array_product <- array1 * 2
print("Array:")
print(array1)
print(paste("Element at position (2, 3):", element))
print("Array after adding 5:")
print(array_sum)
print("Array after multiplying by 2:")
print(array_product)
OUTPUT
18. Operations using data frame
To demonstrate basic operations on a data frame in R, including creating a data frame,
accessing elements, and performing operations.
data <- data.frame(
Name = c("Reena", "Praba", "Abi"),
Age = c(25, 30, 35),
Score = c(85, 90, 95)
)
first_row <- data[1, ]
second_column <- data$Age
data$Passed <- data$Score >= 50
mean_score <- mean(data$Score)
print("Data Frame:")
print(data)
print("First row:")
print(first_row)
print("Second column (Age):")
print(second_column)
print(paste("Mean Score:", mean_score))
OUTPUT
19.Implementation of functions
To demonstrate how to define and use functions in R for performing basic calculations.
calculate_sum_product <- function(a, b, c) {
sum_result <- a + b + c
product_result <- a * b * c
return(list(Sum = sum_result, Product = product_result))
}
compute_series <- function(n) {
n1 <- as.numeric(n)
result <- n1 + (n1 * 11) + (n1 * 111) + (n1 * 1111)
return(result)
}
sum_product <- calculate_sum_product(3, 4, 5)
series_result <- compute_series(2)
print(paste("Sum:", sum_product$Sum))
print(paste("Product:", sum_product$Product))
print(paste("Result of series for n=2:", series_result))
OUTPUT
20. Drawing scatter plot, box plot, violin plot, dot plot, bar plot, line plot
To demonstrate how to create different types of plots using the `ggplot2` library in R.
library(ggplot2)
data <- data.frame(
Category = c("A", "B", "C", "A", "B", "C"),
Value = c(5, 6, 7, 8, 9, 10)
)
# Scatter plot
scatter_plot <- ggplot(data, aes(x = Category, y = Value)) +
geom_point() +
ggtitle("Scatter Plot")
# Box plot
box_plot <- ggplot(data, aes(x = Category, y = Value)) +
geom_boxplot() +
ggtitle("Box Plot")
# Violin plot
violin_plot <- ggplot(data, aes(x = Category, y = Value)) +
geom_violin() +
ggtitle("Violin Plot")
# Dot plot
dot_plot <- ggplot(data, aes(x = Category, y = Value)) +
geom_dotplot(binaxis = 'y', stackdir = 'center') +
ggtitle("Dot Plot")
# Bar plot
bar_plot <- ggplot(data, aes(x = Category, y = Value)) +
geom_bar(stat = "identity") +
ggtitle("Bar Plot")
# Line plot
line_plot <- ggplot(data, aes(x = Category, y = Value)) +
geom_line() +
ggtitle("Line Plot")
print(scatter_plot)
print(box_plot)
print(violin_plot)
print(dot_plot)
print(bar_plot)
print(line_plot)
OUTPUT
21. Geometric Shapes
To demonstrate how to draw simple geometric shapes in R.
plot(1:10, 1:10, type = "n", xlab = "", ylab = "", xlim = c(0, 10), ylim = c(0, 10))
symbols(5, 5, circles = 2, inches = 0.5, add = TRUE, bg = "blue")
text(5, 5, "Circle", pos = 3)
rect(2, 3, 4, 5, col = "red", border = "black")
text(3, 5.5, "Rectangle")
polygon(c(6, 8, 7), c(3, 3, 5), col = "green")
text(7, 5.5, "Triangle")
title("Geometric Shapes")
OUTPUT
22. Data transformations
To demonstrate basic data transformations in R.
library(dplyr)
data <- data.frame(
Name = c("Reena", "Praba", "Abi", "Nandy", "Suguna", "Suba"),
Age = c(25, 30, 22, 28, 26, 24),
Score = c(80, 90, 75, 88, 85, 78),
Gender = c("Female", "Female", "Male", "Female", "Female", "Female")
)
print("Original Data:")
print(data)
# Scale the Score column
data <- data %>%
mutate(Scaled_Score = scale(Score))
# Normalize the Age column
data <- data %>%
mutate(Normalized_Age = (Age - min(Age)) / (max(Age) - min(Age)))
# Convert Gender to factor
data <- data %>%
mutate(Gender = as.factor(Gender))
# Display transformed data
print("Transformed Data:")
print(data)
OUTPUT
23. Finding missing values
To find and replace missing values in R.
data <- data.frame(
Name = c("Reena", "Praba", "Abi", "Nandy", NA, "Suba"),
Age = c(25, 30, NA, 28, 26, 24),
Score = c(80, 90, 75, NA, 85, 78)
)
print("Original Data:")
print(data)
# Check for missing values
missing_count <- sum(is.na(data))
print(paste("Total Missing Values:", missing_count))
# Replace missing values
data$Age[is.na(data$Age)] <- mean(data$Age, na.rm = TRUE)
data$Score[is.na(data$Score)] <- mean(data$Score, na.rm = TRUE)
data$Name[is.na(data$Name)] <- "Unknown"
# Display data after handling missing values
print("Data After Handling Missing Values:")
print(data)
OUTPUT