Ccs353 Mdcs Lab Manual
Ccs353 Mdcs Lab Manual
Reg.No: Semester:
Degree: Branch:
Subject: SubjectCode:
BONAFIDE CERTIFICATE
RegisterNo.
This is to certify that this is a bonafide record of the work done by the above student
with Roll No. of Semester B.E
Degree in in
the
To write the program for Huffman codes for given symbol probabilities using python.
ALGORITHM:
STEP1: Create a leaf node for each unique character & build a min heap of all leaf nodes (Min
Heap is used as a priority queue). The value of frequency field is used to compare two nodes in min
heap. Initially, the least frequent character is at root).
STEP2: Extract two nodes with the minimum frequency from the min heap.
STEP3: Create a new internal node with a frequency equal to the sum of the two nodes
frequencies. Make the first extracted node as its left child & the other extracted node as its right
child. Add this node the min heap.
STEP4: Repeat step 2 and 3 until the heap contains only one node. The remaining node is the root
node and the tree is complete.
Program:
import heapq
class Node:
self.char = char
self.freq = freq
self.left = None
self.right = None
def build_huffman_tree(text):
freq_dict = Counter(text)
heapq.heapify(priority_queue)
right = heapq.heappop(priority_queue)
merged.left = left
merged.right = right
heapq.heappush(priority_queue, merged)
return priority_queue[0]
codes[node.char] = prefix
return codes
encoded_text = ""
encoded_text += codes[char]
return encoded_text
decoded_text = ""
current_node = root
if bit == '0':
current_node = current_node.left
else:
current_node = current_node.right
decoded_text += current_node.char
current_node = root
return decoded_text
def huffman_compress(text):
root = build_huffman_tree(text)
codes = build_huffman_codes(root)
# Example usage:
Output:
Result:
Thus the program executed successfully and the output also verified.
Ex.no.2 Encode run lengths with fixed-length code.
Aim:
ALGORITHM:
PROGRAM:
def encode(message):
encoded_message = ""
i=0
count = 1
ch = message[i]
j=i
if (message[j] == message[j+1]):
count = count+1
j = j+1
else:
break
encoded_message=encoded_message+str(count)+ch
i = j+1
return encoded_message
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message)
OUTPUT:
1A4B8C1A1B
RESULT
EX.NO.3 Lempel-Ziv algorithm for adaptive variable-length encoding
Aim:
To write a Lempel Ziv algorithm for adaptive variable-length encoding using python coding.
ALGORITHM:
PROGRAM:
keys=[]
index=0
t=time.time()
def sub_strin_check(text,index_num):
n=1
while True:
substring = text[index_num:index_num+n]
print(substring)
keys.append(substring)
# print(keys[-1])
return (index_num+n)
else:
n = n+1
continue
while True:
try:
# print (index)
keys.append(text[index])
print(keys.append(text[index]),text[index])
except:
break
else:
try:
index = sub_strin_check(text,index)
print(index)
print(index)
index = index + 1
except:
break
res = str(keys)
print(res)
with open("result","w") as f:
f.write(res)
OUTPUT:
['A', 'A', 'AA', 'AB', 'C', 'C', 'CD', 'ABC', 'ABCA', 'ABCD', 'E', 'E', 'EE', 'EEC', 'B', 'B', 'BB', 'BBD',
'AAE']
RESULT:
Thus the program was executed successfully and the output also verified.
EX.NO:4 Compress the given word using arithmetic coding based on the frequency of the letters
AIM:
ALGORITHM:
Step1: Initialization:
Step2:Define a probability model that assigns probabilities to each symbol in the input
alphabet.
Step3:Initialize a range [0, 1) to represent the entire symbol space.
Step4:Symbol Encoding:
Step5:For each symbol in the input sequence:
Step6:Determine the symbol's probability range within the current range.
Step7:Scale the current range to match the probability range of the symbol.
Step8:Update the current range to the scaled subrange of the symbol.
Step9:The final range after encoding represents the entire input sequence with a single
floating-point number.
Step10:Output Encoding:
Step11:output the final range as a floating-point number.
Step12:Decoding (Optional):
Step13:To decode the compressed data:
Step14:Initialize the range to [0, 1) and accumulate the encoded floating-point number.
Step15:Iterate through the input symbols, reversing the encoding process to reconstruct the
original input sequence.
PROGRAM:
F cumulative_freq(freq)
[Int = Int] cf
V total = 0
L(b) 256
I b C freq
cf[b] = total
total += freq[b]
R cf
F arithmethic_coding(bytes, radix)
DefaultDict[Int, Int] freq
L(b) bytes
freq[b.code]++
V cf = cumulative_freq(freq)
BigInt lower = 0
BigInt pf = 1
L(b) bytes
pf *= freq[b.code]
V upper = lower + pf
BigInt power = 0
pf I/= radix
I pf == 0
L.break
power++
V base = sum(freq.values())
V cf = cumulative_freq(freq)
L(k, v) cf
dict[v] = k
Int? lchar
I i C dict
lchar = dict[i]
E I lchar != N
dict[i] = lchar
V decoded = ‘’
power = BigInt(base) ^ i
V fv = freq[c]
V cv = cf[c]
enc = rem
R decoded
V radix = 10
I str != dec
OUTPUT:
DABDDB => 251 * 10^2
RESULT:
Thus the program executed successfully and the output also verified.
Ex. No:5 Write a program to split images from a video without using any primitives
AIM:
To implement the split images from a video without using any primitives.
ALGORITHM:
STEP1:Import the necessary libraries, in this case, OpenCV for video processing and os for file
operations.
STEP2: Define a function split_video_into_frames that takes the path to the video file
(video_path) and the output folder (output_folder) as input parameters.
STEP4: Verify if the video file was opened successfully using isOpened().
PROGRAM:
# Importing all necessary libraries
import cv2
import os
try:
# frame
currentframe = 0
while(True):
if ret:
# if video is still left continue creating images
name = './data/frame' + str(currentframe) + '.jpg'
print ('Creating...' + name)
OUTPUT
Thus the program executed successfully and the output also verified.
ALGORITHM:
PROGRAM:
import sched
import time
class DataStreamScheduler:
def __init__(self):
self.scheduler = sched.scheduler(time.time, time.sleep)
def start(self):
self.scheduler.run()
if __name__ == "__main__":
scheduler = DataStreamScheduler()
Output:
Processing data stream: Stream 3
Processing data stream: Stream 2
Processing data stream: Stream 1
RESULT:
Thus the program executed successfully and the output also verified.
Ex.No:7 Write the code for identifying the popularity of content retrieval from media server.
Date:
AIM:
To implement the code for identifying the popularity of content retrievel from media server.
ALGORITHM:
PROGRAM:
Output:
RESULT:
Thus the program executed successfully and the output also verified.
EX.NO: 8 Write the code for ensuring data availability in disks using strip based method.
Date:
________________________________________________________________________________
AIM:
To implement the program for ensuring data availability in disks using strip based method.
ALGORITHM:
STEP1: Choose the RAID level based on redundancy and performance requirements.
STEP2:Divide data into stripes (blocks) based on the RAID stripe size.
STEP3:Distribute stripes across disks:
RAID 0: Distribute stripes evenly across disks.
RAID 1: Mirror stripes across disks.
RAID 5: Distribute data and parity stripes across disks.
Other RAID levels: Distribute data and redundancy information accordingly.
STEP4: Monitor disk health and redundancy.
STEP5: Replace failed disks and rebuild data using redundancy information.
STEP6: Optionally, use hot spare disks and implement proactive monitoring for enhanced
availability.
Step7: Perform regular maintenance and backups for data protection and recovery.
PROGRAM:
class RAIDStrip:
def __init__(self, num_disks, strip_size):
self.num_disks = num_disks
self.strip_size = strip_size
self.disks = [[] for _ in range(num_disks)]
def read_data(self):
reconstructed_data = []
for strip_index in range(len(self.disks[0])):
for disk_index in range(self.num_disks):
strip = self.disks[disk_index][strip_index]
reconstructed_data.append(strip)
return ''.join(reconstructed_data)
def print_disks(self):
for i, disk in enumerate(self.disks):
print(f"Disk {i+1}: {disk}")
if __name__ == "__main__":
num_disks = 4
strip_size = 4
raid = RAIDStrip(num_disks=num_disks, strip_size=strip_size)
OUTPUT:
Disk 1: ['H', 'o', 'h', 'i', 'o', 't', ' ', 'a', 'r', 'I', 't', 'i']
Disk 2: ['e', ',', 'i', 's', 'm', 'e', 'd', ' ', ' ', 'D', 'r', 'n']
Disk 3: ['l', ' ', 's', ' ', 'e', 's', 'a', 'f', 'R', ' ', 'i', 'g']
Disk 4: ['l', 't', ' ', 's', ' ', 't', 't', 'o', 'A', 's', 'p', '!']
Retrieved data: Hello, this is some test data for RAID striping!
RESULT:
Thus the program executed successfully and the output also verified.
Ex.no:9 Write a program to convert all images to gif images without using any primitives
Date:
AIM:
To implement the program to convert all the images to gif images without using any primitives.
ALGORITHM:
STEP1: Import necessary libraries for image processing and GIF creation (e.g., PIL, imageio).
STEP2: Load all input images from the provided file paths.
STEP3: Convert each loaded image to the GIF-compatible format.
Resize images if necessary to ensure consistent dimensions.
Convert images to the appropriate color mode (e.g., RGB).
STEP4:Create a GIF file and initialize it with the first image.
Set parameters such as duration (time interval between frames) and loop count if needed.
STEP5: For each remaining image:
Append the image as a new frame to the GIF file.
Ensure that the frame duration matches the desired timing.
STEP6:Save the GIF file with the specified output file name.
STEP7:The output is a GIF file containing all input images.
PROGRAM:
from PIL import Image
import os
# Open each JPG image in the input folder and append it to the images list
for filename in os.listdir(input_folder):
if filename.endswith(".jpg"):
img_path = os.path.join(input_folder, filename)
images.append(Image.open(img_path))
# Specify the input folder containing JPG images and the output GIF file path
input_folder = "/var/pictures"
output_file = "output.gif"
OUTPUT:
RESULT:
Thus the program executed successfully and the output also verified.