0% found this document useful (0 votes)
26 views

Discrete Structure Lab Work

Uploaded by

Yubraj Khatiwada
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Discrete Structure Lab Work

Uploaded by

Yubraj Khatiwada
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

MCA501 Discrete structure

MCA501 Discrete Structure

Tribhuvan University
Faculty of Humanities and Social Sciences
Master in Computer Application

Submitted to
Bishnu Khadka
Department of Computer Application
Patan Multiple Campus
Patan Dhoka, Lalitpur

Submitted by
Yubraj Khatiwada
MCA 1st Semester
Symbol No: 2285030

Yubraj Khatiwada
MCA501 Discrete structure

Contents
Proposition Logic: ................................................................................................................................... 2

1. Find the propositional formula and truth table and check whether tautology exists. ....................... 2

Recursion ................................................................................................................................................. 4

2. Write a program to find the Fibonacci series. .................................................................................. 4

Number Theory ....................................................................................................................................... 5

3. Find the GCD of any two integers using the Euclidean theorem. .................................................... 5

4. Find the multiplicative inverse of b in zn using the extended Euclidean theorem. .......................... 6

Recurrence Relation ................................................................................................................................ 7

5. Write a program to implement recurrence relation. Like Factorial. ................................................. 7

Relation and Graph ................................................................................................................................. 8

6. Write a program to implement minimum cost-spanning tree algorithms using Prims..................... 8

7. Write a program to implement minimum cost-spanning tree algorithms using Kruskal .............. 10

8. Write a program to implement a shortest-path algorithm like Dijkstra.......................................... 12

Finite Automata .................................................................................................................................... 14

9. Write a program for the implementation of DFA on the string that accepts, starting with
0 and ending with 1 over input alphabet {0,1}. ............................................................................. 14

10. Write a program to validate the E-mail, Mobile no and Identifiers using regular
expression....................................................................................................................................... 16

Yubraj Khatiwada
MCA501 Discrete structure

Proposition Logic:
1. Find the propositional formula and truth table and check whether tautology exists.

Import itertools

# Function to evaluate a formula with given values for variables

def evaluate_formula(formula, variables, values):


# Create a dictionary to map each variable to its respective truth value
assignment = dict(zip(variables, values))
# Evaluate the formula with the given truth
assignments return eval(formula, {}, assignment)
# Function to generate truth table and check if a formula is a tautology
def truth_table_and_tautology(formula):
# Extract unique variables in the formula variables =
sorted(set(filter(str.isalpha, formula)))
# Generate all possible combinations of truth values for the variables
combinations = list(itertools.product([True, False], repeat=len(variables)))
# Prepare a list to store the results of each row in the truth table
truth_values = []
# Print the header of the truth table
print("Truth Table:")
print(" | ".join(variables) + " | " + formula)

print("-" * (len(variables) * 6 + len(formula) + 5))


# Evaluate the formula for each combination of truth values for
values in combinations:[
result = evaluate_formula(formula, variables, values)
truth_values.append(result)
# Print each row of the truth table
row = " | ".join(map(str, values)) + " | " + str(result)
print(row)
# Check if the formula is a tautology
if all(truth_values):
print("\nThe formula is a tautology (True in all cases).")
else:
print("\nThe formula is not a tautology.")

2 Yubraj Khatiwada
MCA501 Discrete structure

# Input: Propositional formula (use Python syntax)


formula = input("Enter the propositional formula (e.g., 'A or not B and C'): ")
truth_table_and_tautology(formula)

Output:-
Truth Table:
a|a

True | True
False | False

The formula is not a tautology.

3 Yubraj Khatiwada
MCA501 Discrete structure

Recursion
2. Write a program to find the Fibonacci series.

def fibonacci_series(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence[:n]

# Input: number of terms


n = int(input("Enter the number of terms: "))

print("Fibonacci Series:", fibonacci_series(n))

Output :

Enter the number of terms: 6


Fibonacci Series: [0, 1, 1, 2, 3, 5]

4 Yubraj Khatiwada
MCA501 Discrete structure

Number Theory
3. Find the GCD of any two integers using the Euclidean theorem.

def gcd(a, b):


while b != 0:
a, b = b, a % b
return a

# Input: Two numbers


num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number:"))

# Output the GCD


print(f"The GCD of {num1} and {num2} is: {gcd(num1, num2)}")

Output :
Enter the first number: 25
Enter the second number: 150
The GCD of 25 and 150 is:25

5 Yubraj Khatiwada
MCA501 Discrete structure

4. Find the multiplicative inverse of b in zn using the extended Euclidean theorem.

def extended_gcd(a, b):


if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y

def multiplicative_inverse(b, n):


gcd, x, y = extended_gcd(b, n)
if gcd != 1:
return None # Inverse does not exist if gcd(b, n) != 1
else:
# Ensure x is positive
return x % n

# Input: Values of b and n


b = int(input("Enter the value of b: "))
n = int(input("Enter the value of n: "))

inverse = multiplicative_inverse(b, n)

if inverse is None:
print(f"The multiplicative inverse of {b} modulo {n} does not exist.")

else:
print(f"The multiplicative inverse of {b} modulo {n} is: {inverse}")

Output :
Enter the value of b: 4
Enter the value of n: 11
The multiplicative inverse of 4 modulo 11 is: 3

6 Yubraj Khatiwada
MCA501 Discrete structure

Recurrence Relation
5. Write a program to implement recurrence relation. Like Factorial.

def factorial(n):
if n == 0:
return 1 # Base case: 0! = 1
else:
return n * factorial(n - 1) # Recursive call

# Input: Number for which factorial is to be calculated


num = int(input("Enter a number: "))
# Output: Factorial of the number
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"The factorial of {num} is: {factorial(num)}")

Output :
Enter a number: 5
The factorial of 5 is: 120

7 Yubraj Khatiwada
MCA501 Discrete structure

Relation and Graph


6. Write a program to implement minimum cost-spanning tree algorithms using Prims

import sys
# Prim's algorithm to find the minimum spanning tree
def prims_mst(graph):
num_nodes = len(graph)
selected_node = [False] * num_nodes
mst_edges = []
total_cost = 0

# Start from node 0


selected_node[0] = True
for _ in range(num_nodes - 1):
min_edge = (None, None, sys.maxsize) # (from_node, to_node, cost)

# Find the minimum edge connecting the MST with a new node
for i in range(num_nodes):
if selected_node[i]:
# Node is part of the MST
for j in range(num_nodes):
if not selected_node[j] and graph[i][j] > 0:
# Not in MST and edge exists
if graph[i][j] < min_edge[2]:
min_edge = (i, j, graph[i][j])

# Add the selected minimum edge to the MST


from_node, to_node, cost = min_edge
selected_node[to_node] = True
mst_edges.append((from_node, to_node, cost))
total_cost += cost
print("Edges in the MST with their weights:")
for from_node, to_node, cost in mst_edges:
print(f"{from_node} -- {to_node} == {cost}")
print("Total cost of MST:", total_cost)

8 Yubraj Khatiwada
MCA501 Discrete structure

graph = [
[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]

prims_mst(graph)

Output :
Edges in the MST with their weights:
0 -- 1 == 2
1 -- 2 == 3
1 -- 4 == 5
0 -- 3 == 6
Total cost of MST: 16

9 Yubraj Khatiwada
MCA501 Discrete structure

7. Write a program to implement minimum cost-spanning tree algorithms using Kruskal

def find(parent, i):


if parent[i] == i:
return i
return find(parent, parent[i])

# Function to perform union of two sets


def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1

# Kruskal's algorithm to find the minimum spanning tree


def kruskal_mst(nodes, edges):
edges.sort(key=lambda x: x[2]) # Sort edges by weight
parent = []
rank = []

# Initialize union-find structure


for node in range(nodes):
parent.append(node)
rank.append(0)
mst_edges = []
total_cost = 0
for edge in edges:
u, v, weight = edge
root u=find(parent, u)
root_v = find(parent, v)

10 Yubraj khatiwada
# If including this edge doesn't form a cycle, add it to the MST
if root_u != root_v:
mst_edges.append((u, v, weight))
total_cost += weight
union(parent, rank, root_u, root_v)

print("Edges in the MST with their weights:")


for u, v, weight in mst_edges:
print(f"{u} -- {v} == {weight}")
print("Total cost of MST:", total_cost)

# Example graph represented as a list of edges


nodes = 5
edges = [
(0, 1, 2),
(0, 3, 6),
(1, 2, 3),
(1, 3, 8),
(1, 4, 5),
(2, 4, 7),
(3, 4, 9)]
kruskal_mst(nodes, edges)

Output :
Edges in the MST with their weights:
0 -- 1 == 2
1 -- 2 == 3
1 -- 4 == 5
0 -- 3 == 6
Total cost of MST: 16

11 Yubraj Khatiwada
MCA501 Discrete structure

8. Write a program to implement a shortest-path algorithm like Dijkstra.


import heapq
# Function to implement Dijkstra's algorithm

def dijkstra(graph, start):


# Number of nodes
num_nodes = len(graph)
# Distance array: Initialize all distances as infinity, except for the start node
distances = [float("inf")] * num_nodes
distances[start] = 0

# Priority queue to store (distance, node) pairs


priority_queue = [(0, start)] # (distance from start, node)
while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)

# If the current distance is greater than the recorded shortest distance, skip
if current_distance > distances[current_node]:
continue

# Explore neighbors of the current node


for neighbor, weight in graph[current_node]:
distance = current_distance + weight
# If a shorter path is found, update the distance and add to the queue
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
# Return the computed shortest distances
return distances
# Example graph represented as an adjacency list
# Each list element contains pairs (neighbor, weight)

12 Yubraj Khatiwada
MCA501 Discrete structure

graph = {
0: [(1, 4), (2, 1)],
1: [(3, 1)],
2: [(1, 2), (3, 5)],
3: [] }

# Input: Starting node


start_node = int(input("Enter the starting node: "))

# Output:
Shortest path from start node to all other nodes
shortest_distances = dijkstra(graph, start_node)
for node, distance in enumerate(shortest_distances):
print(f"Shortest distance from node {start_node} to node {node} is {distance}")

Output :

Enter the starting node: 2


Shortest distance from node 2 to node 0 is inf
Shortest distance from node 2 to node 1 is 2
Shortest distance from node 2 to node 2 is 0
Shortest distance from node 2 to node 3 is 3

13 Yubraj Khatiwada
MCA501 Discrete structure

Finite Automata
9. Write a program for the implementation of DFA on the string that accepts,
starting with 0 and ending with 1 over input alphabet {0,1}.

Def dfa_accepts_string(s):
# Initial state
current_state = "q0"
# Process each character in the string for char in s:
if current_state == "q0":
if char == '0':
current_state = "q1"
elif char == '1':
current_state = "q0"

# Stay in q0 if starts with 1

elif current_state == "q1":


if char == '0':
current_state = "q1"
elif char == '1':
current_state = "q2"

elif current_state == "q2":


# Stay in q2 (accepting state) for any input

current_state = "q2"
# Accept if we end in the accepting state q2
return current_state == "q2"
# Input: Test strings
test_strings = [
"001", # Accepted
"01", # Accepted
"10", # Rejected
"0001", # Accepted
"0111", # Accepted

14 Yubraj Khatiwada
MCA501 Discrete structure

"110", # Rejected
"0", # Rejected
"1", # Rejected ]

# Test each string for s in test_strings:


result = "Accepted" if dfa_accepts_string(s)
else "Rejected"
print(f"String '{s}': {result}")

Output :
String '001': Accepted
String '01': Accepted
String '10': Rejected
String '0001': Accepted
String '0111': Accepted
String '110': Rejected
String '0': Rejected
String '1': Rejected

15 Yubraj Khatiwada
MCA501 Discrete structure

10. Write a program to validate the E-mail, Mobile no and Identifiers using regular expression

import re
# Function to validate an email address

def validate_email(email):
# Email pattern: basic format with alphanumeric characters, underscores, periods, etc.
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
if re.match(pattern, email):
return "Valid email"
else:
return "Invalid email"

# Function to validate a mobile number that starts with 98 or 97 and has 10 digits
def validate_mobile(mobile):
# Mobile pattern: starts with 98 or 97, followed by 8 other digits
pattern = r'^(98|97)\d{8}$'
if re.match(pattern, mobile):
return "Valid mobile number"
else:
return "Invalid mobile number"

# Function to validate a programming identifier


def validate_identifier(identifier):
pattern = r'^[a-zA-Z_][a-zA-Z0-9_]*$'
if re.match(pattern, identifier):
return"Valididentifier"
else:
return "Invalid identifier"

# Testing the functions with various inputs


emails = ["[email protected]", "[email protected]", "invalid-email@",
"user@domain"]
mobiles = ["9805353171", "9811383812", "9612345678", "97123", "12345"]
identifiers = ["_validIdentifier", "2invalid", "valid_id", "anotherValidIdentifier", "invalid-id"]

16 Yubraj Khatiwada
MCA501 Discrete structure

print("Email Validation:")
for email in emails:
print(f"{email}: {validate_email(email)}")

print("\nMobile Number Validation:")


for mobile in mobiles:
print(f"{mobile}: {validate_mobile(mobile)}")

print("\nIdentifierValidation:")
for identifier in identifiers:
print(f"{identifier}: {validate_identifier(identifier)}")

Output:
Email Validation: [email protected]: Valid email
[email protected]:
Valid email invalid-email@:
Invalid email user@domain:
Invalid email
Mobile Number Validation:
905353171: Valid mobile
number 9811383812: Valid
mobile number 9612345678:
Invalid mobile number 98123:
Invalid mobile number
12345: Invalid mobile number
Identifier Validation:
_validIdentifier: Valid
identifier 2invalid:
Invalid identifier
valid_id: Valid
identifier
anotherValidIdentifier: Valid
identifier invalid-id: Invalid
identifier

17 Yubraj Khatiwada

You might also like