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

Dstl Solution

The document outlines a series of programming experiments for a Computer Science lab, focusing on Python programming concepts such as data types, operators, decision-making, loops, and set operations. It includes detailed implementations for calculating quadratic roots, factorials, sums of natural numbers, and various set operations, along with examples and outputs. Additionally, it covers properties of relations like reflexivity, symmetry, and transitivity, as well as recursive sequences for polynomials and Fibonacci numbers.

Uploaded by

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

Dstl Solution

The document outlines a series of programming experiments for a Computer Science lab, focusing on Python programming concepts such as data types, operators, decision-making, loops, and set operations. It includes detailed implementations for calculating quadratic roots, factorials, sums of natural numbers, and various set operations, along with examples and outputs. Additionally, it covers properties of relations like reflexivity, symmetry, and transitivity, as well as recursive sequences for polynomials and Fibonacci numbers.

Uploaded by

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

SCHOOL OF ENGINEERING &TECHNOLOGY

Department of Computer Science & Engineering

LAB NAME : DSTL Lab

LAB CODE : (SECS-353P)

LIST OF EXPERIMENTS

1. Implementa on basic python program related to Data types, operators.

a) Evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3


# Define the value of x

x=3

# Calculate the expression

result = 2 * x**3 - 6 * x**2 + 2 * x - 1

# Print the result

print(f"The value of the expression for x = {x} is: {result}")

output:
The value of the expression for x = 3 is: 9
b) Write a Python program to find the roots of a quadra c func on
import cmath # Import cmath for complex number calcula ons

def quadra c_roots(a, b, c):

"""Calculates the roots of a quadra c equa on ax^2 + bx + c = 0

Args:

a: Coefficient of the quadra c term (x^2)

b: Coefficient of the linear term (x)


c: Constant term

Returns:

A tuple containing the two roots (possibly complex)

"""

# Calculate the discriminant

discriminant = (b**2) - 4 * (a * c)

# Calculate the roots

if discriminant >= 0:

root1 = (-b + discriminant**0.5) / (2 * a)

root2 = (-b - discriminant**0.5) / (2 * a)

else:

root1 = (-b + cmath.sqrt(discriminant)) / (2 * a)

root2 = (-b - cmath.sqrt(discriminant)) / (2 * a)

return (root1, root2)

# Get input from the user

a = float(input("Enter the coefficient of x^2: "))

b = float(input("Enter the coefficient of x: "))

c = float(input("Enter the constant term: "))

# Find the roots

root1, root2 = quadra c_roots(a, b, c)

# Print the results in a clear format

print("-" * 20)

print("Quadra c Equa on: {}x^2 + {}x + {} = 0".format(a, b, c))

print("-" * 20)

print(f"Root 1: {root1}")
print(f"Root 2: {root2}")

print("-" * 20)

output:

Quadra c Equa on: 1.0x^2 + -5.0x + 6.0 = 0

Root 1: (3+0j)

Root 2: (2+0j)

c) ax2 + bx + c= 0, where a, b and c are real numbers and a ≠ 0

The quadra c equa on:

ax^2 + bx + c = 0

where a, b, and c are real numbers and a ≠ 0.

Quadra c Formula:

x = (-b ± √(b^2 - 4ac)) / 2a

Steps to Solve:

1. Write down the equa on.

2. Iden fy coefficients a, b, and c.

3. Calculate the discriminant (Δ) = b^2 - 4ac.

4. Determine the nature of roots based on Δ.

5. Apply the quadra c formula.

Nature of Roots:

1. Δ > 0: Two dis nct real roots.

2. Δ = 0: One repeated real root.

3. Δ < 0: Complex conjugate roots.

Example:

Solve x^2 + 5x + 6 = 0.

1. a = 1, b = 5, c = 6.

2. Δ = 5^2 - 4(1)(6) = 25 - 24 = 1.
3. Since Δ > 0, two dis nct real roots exist.

4. Apply quadra c formula:

x = (-(5) ± √(1)) / 2(1)

x = (-5 ± 1) / 2

x = -2 or x = -3

Roots: x = -2, x = -3

2. Implementa on of decision, Loop in python.

a) Write a program to calculate factorial of a number.

def factorial(n):

if n < 0:

return "Factorial is not defined for nega ve numbers."

elif n == 0 or n == 1:

return 1

else:

result = 1

for i in range(2, n + 1):

result *= i

return result

# Get user input

try:

number = int(input("Enter a non-nega ve integer: "))

result = factorial(number)

print(f"The factorial of {number} is: {result}")

except ValueError:

print("Please enter a valid integer.")

output:
Enter a non-nega ve integer: 5
The factorial of 5 is: 120

b) Write a program to calculate sum of first n natural numbers where n is finite.

def sum_of_natural_numbers(n):

if n < 0:

return "The sum is not defined for nega ve numbers."

else:

return n * (n + 1) // 2 # Using the formula n(n + 1)/2

# Get user input

try:

number = int(input("Enter a non-nega ve integer (n): "))

result = sum_of_natural_numbers(number)

print(f"The sum of the first {number} natural numbers is: {result}")

except ValueError:

print("Please enter a valid integer.")

OUTPUT:

Enter a non-nega ve integer (n): 5


The sum of the first 5 natural numbers is: 15
C) Write a program for cube sum of first n natural numbers where n is finite.

def cube_sum_of_natural_numbers(n):

if n < 0:

return "The sum is not defined for nega ve numbers."

else:

return (n * (n + 1) // 2) ** 2 # Using the formula (n(n + 1)/2)^2

# Get user input


try:

number = int(input("Enter a non-nega ve integer (n): "))

result = cube_sum_of_natural_numbers(number)

print(f"The sum of the cubes of the first {number} natural numbers is: {result}")

except ValueError:

print("Please enter a valid integer.")

OUTPUT:
Enter a non-nega ve integer (n): 3
The sum of the cubes of the first 3 natural numbers is: 36

3. Implementa on of various set opera ons (union, intersec on, difference, symmetric difference,
Power set, cardinality).

Python Program for Various Set Opera ons

from itertools import chain, combina ons

def union(set1, set2):

return set1 | set2

def intersec on(set1, set2):

return set1 & set2

def difference(set1, set2):

return set1 - set2

def symmetric_difference(set1, set2):

return set1 ^ set2


def power_set(s):

"""Returns the power set of a given set."""

power_set_list = list(chain.from_iterable(combina ons(s, r) for r in range(len(s) + 1)))

return [set(subset) for subset in power_set_list]

def cardinality(s):

"""Returns the cardinality of a set."""

return len(s)

# Example sets

set1 = {1, 2, 3, 4}

set2 = {3, 4, 5, 6}

# Performing set opera ons

print(f"Set 1: {set1}")

print(f"Set 2: {set2}\n")

print(f"Union: {union(set1, set2)}")

print(f"Intersec on: {intersec on(set1, set2)}")

print(f"Difference (Set1 - Set2): {difference(set1, set2)}")

print(f"Symmetric Difference: {symmetric_difference(set1, set2)}")

print(f"Power Set of Set 1: {power_set(set1)}")

print(f"Cardinality of Set 1: {cardinality(set1)}")

print(f"Cardinality of Set 2: {cardinality(set2)}")

Explana on of the Func ons:

1. Union: Combines all unique elements from both sets.

def union(set1, set2):

return set1 | set2

2. Intersec on: Finds common elements between both sets.

def intersec on(set1, set2):


return set1 & set2

3. Difference: Returns elements that are in the first set but not in the second.
def difference(set1, set2):
return set1 - set2

4. Symmetric Difference: Returns elements that are in either of the sets but not in both.
def symmetric_difference(set1, set2):
return set1 ^ set2

5. Power Set: Generates the power set, which is the set of all subsets of a given set.
def power_set(s):
power_set_list = list(chain.from_iterable(combina ons(s, r) for r in range(len(s) + 1)))
return [set(subset) for subset in power_set_list]

6. Cardinality: Returns the number of elements in a set.


def cardinality(s):
return len(s)

Example Output:

Set 1: {1, 2, 3, 4}
Set 2: {3, 4, 5, 6}

Union: {1, 2, 3, 4, 5, 6}
Intersec on: {3, 4}
Difference (Set1 - Set2): {1, 2}
Symmetric Difference: {1, 2, 5, 6}
Power Set of Set 1: [set(), {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}, {1, 2, 3}, {1,
2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}]
Cardinality of Set 1: 4
Cardinality of Set 2: 4

4. Write program to perform following opera on:

a) Is the given rela on is reflexive?

def is_reflexive(rela on, elements):

for element in elements:

if (element, element) not in rela on:

return False

return True

# Example usage
# Define the set of elements

elements = {1, 2, 3}

# Define a rela on as a set of tuples

# Example of a reflexive rela on

rela on_reflexive = {(1, 1), (2, 2), (3, 3), (1, 2), (2, 3)}

# Example of a non-reflexive rela on

rela on_non_reflexive = {(1, 1), (2, 2), (1, 2), (2, 3)}

# Check reflexivity

print(f"Is the rela on {rela on_reflexive} reflexive? {is_reflexive(rela on_reflexive, elements)}")

print(f"Is the rela on {rela on_non_reflexive} reflexive? {is_reflexive(rela on_non_reflexive,


elements)}")

Output:

Is the rela on {(1, 1), (2, 2), (3, 3), (1, 2), (2, 3)} reflexive? True

Is the rela on {(1, 1), (2, 2), (1, 2), (2, 3)} reflexive? False

b) Is the given rela on is symmetric?

def is_symmetric(rela on):

for (a, b) in rela on:

if (b, a) not in rela on:

return False

return True

# Example usage

# Define a rela on as a set of tuples

# Example of a symmetric rela on

rela on_symmetric = {(1, 2), (2, 1), (3, 3)}

# Example of a non-symmetric rela on

rela on_non_symmetric = {(1, 2), (2, 3), (3, 1)}


# Check symmetry

print(f"Is the rela on {rela on_symmetric} symmetric?


{is_symmetric(rela on_symmetric)}")

print(f"Is the rela on {rela on_non_symmetric} symmetric?


{is_symmetric(rela on_non_symmetric)}")

OUTPUT:

Is the rela on {(1, 2), (2, 1), (3, 3)} symmetric? True

Is the rela on {(1, 2), (2, 3), (3, 1)} symmetric? False

c) Is the given rela on is Transi ve?

def is_transi ve(rela on):

# Convert rela on to a list for easier indexing

rela on_list = list(rela on)

for (a, b) in rela on_list:

for (x, c) in rela on_list:

if b == x: # Check for transi ve pairs

if (a, c) not in rela on:

return False

return True

# Example usage

# Define a rela on as a set of tuples

# Example of a transi ve rela on

rela on_transi ve = {(1, 2), (2, 3), (1, 3)}

# Example of a non-transi ve rela on

rela on_non_transi ve = {(1, 2), (2, 3), (3, 1)}

# Check transi vity

print(f"Is the rela on {rela on_transi ve} transi ve? {is_transi ve(rela on_transi ve)}")

print(f"Is the rela on {rela on_non_transi ve} transi ve? {is_transi ve(rela on_non_transi ve)}")
OUTPUT:

Is the rela on {(1, 2), (2, 3), (1, 3)} transi ve? True

Is the rela on {(1, 2), (2, 3), (3, 1)} transi ve? False

5. Write program to generate recursive sequence of a closed formula and also calculate its value at
par cular non nega ve integer recursively for the following:

a) Polynomial 2n

def polynomial_2n(n):

"""Calculate the polynomial 2n recursively."""

if n < 0:

raise ValueError("n must be a non-nega ve integer.")

if n == 0:

return 0 # Base case: 2 * 0 = 0

else:

return 2 + polynomial_2n(n - 1) # Recursive case: 2 + 2 * (n - 1)

# Example usage

if __name__ == "__main__":

# Calculate polynomial 2n for a specific non-nega ve integer

n = 5 # You can change this value to test with other non-nega ve integers

result = polynomial_2n(n)

print(f"The value of the polynomial 2n at n={n} is: {result}")

OUTPUT:

The value of the polynomial 2n at n=5 is: 10


b) Fibonacci sequence Factorial of a number

def fibonacci(n):
"""Calculate the nth Fibonacci number recursively."""

if n < 0:

raise ValueError("n must be a non-nega ve integer.")

if n == 0:

return 0 # Base case: F(0) = 0

elif n == 1:

return 1 # Base case: F(1) = 1

else:

return fibonacci(n - 1) + fibonacci(n - 2) # Recursive case

def factorial(n):

"""Calculate the factorial of n recursively."""

if n < 0:

raise ValueError("n must be a non-nega ve integer.")

if n == 0 or n == 1:

return 1 # Base case: 0! = 1! = 1

else:

return n * factorial(n - 1) # Recursive case

# Example usage

if __name__ == "__main__":

# Calculate Fibonacci for a specific non-nega ve integer

fib_n = 6 # You can change this value to test with other non-nega ve integers

fib_value = fibonacci(fib_n)

print(f"The {fib_n}th Fibonacci number is: {fib_value}")

# Calculate factorial for a specific non-nega ve integer

fact_n = 5 # You can change this value to test with other non-nega ve integers

fact_value = factorial(fact_n)

print(f"The factorial of {fact_n} is: {fact_value}")


OUTPUT:

The 6th Fibonacci number is: 8

The factorial of 5 is: 120

6. Write program to:

a. Perform + m (addi on modulo) and xm (mul plica on modulo)for a par cular set.

def addi on_modulo(numbers, m):

"""Perform addi on modulo m on a list of numbers."""

total = 0

for num in numbers:

total = (total + num) % m

return total

def mul plica on_modulo(numbers, m):

"""Perform mul plica on modulo m on a list of numbers."""

product = 1

for num in numbers:

product = (product * num) % m

return product

# Example usage

if __name__ == "__main__":

# Define a set of numbers and a modulus

numbers = [5, 10, 15] # You can change this list to test with other sets of numbers

m = 7 # Modulus

# Perform addi on modulo

add_result = addi on_modulo(numbers, m)

print(f"Addi on modulo {m} of {numbers} is: {add_result}")


# Perform mul plica on modulo

mult_result = mul plica on_modulo(numbers, m)

print(f"Mul plica on modulo {m} of {numbers} is: {mult_result}")

OUTPUT:

Addi on modulo 7 of [5, 10, 15] is: 3

Mul plica on modulo 7 of [5, 10, 15] is: 1

b. Check closure property for + m (addi on modulo)


and xm

def check_addi on_modulo_closure(numbers, m):

"""Check closure property for addi on modulo m."""

for i in range(len(numbers)):

for j in range(len(numbers)):

result = (numbers[i] + numbers[j]) % m

if result not in numbers:

print(f"Closure under addi on modulo {m} fails for: ({numbers[i]} + {numbers[j]}) % {m} =
{result}")

return False

print(f"Closure under addi on modulo {m} holds for the set: {numbers}")

return True

def check_mul plica on_modulo_closure(numbers, m):

"""Check closure property for mul plica on modulo m."""

for i in range(len(numbers)):

for j in range(len(numbers)):

result = (numbers[i] * numbers[j]) % m

if result not in numbers:

print(f"Closure under mul plica on modulo {m} fails for: ({numbers[i]} * {numbers[j]}) %
{m} = {result}")

return False

print(f"Closure under mul plica on modulo {m} holds for the set: {numbers}")
return True

# Example usage

if __name__ == "__main__":

# Define a set of numbers and a modulus

numbers = [0, 1, 2, 3, 4] # You can change this list to test with other sets of numbers

m = 5 # Modulus

# Check closure for addi on modulo

check_addi on_modulo_closure(numbers, m)

# Check closure for mul plica on modulo

check_mul plica on_modulo_closure(numbers, m)

OUTPUT:

Closure under addi on modulo 5 holds for the set: [0, 1, 2, 3, 4]

Closure under mul plica on modulo 5 holds for the set: [0, 1, 2, 3, 4]

9. Write program to implement Birthday Problem.

def birthday_problem(n):

# Total days in a year

days_in_year = 365

# If there are more than 365 people, the probability is 100%

if n > days_in_year:

return 1.0

# Calculate the probability of no shared birthdays

probability_no_shared_birthdays = 1.0

for i in range(n):
probability_no_shared_birthdays *= (days_in_year - i) / days_in_year

# Probability of at least one shared birthday

probability_shared_birthday = 1 - probability_no_shared_birthdays

return probability_shared_birthday

# Example usage

if __name__ == "__main__":

# Number of people

n = 23

probability = birthday_problem(n)

print(f"The probability of at least two people sharing a birthday in a group of {n} people is:
{probability:.4f}")

# You can test for different values of n

for i in range(1, 101, 10): # Tes ng for groups of 1, 11, 21, ..., 91

probability = birthday_problem(i)

print(f"Group size: {i}, Probability: {probability:.4f}")

OUTPUT:

The probability of at least two people sharing a birthday in a group of 23 people is: 0.5073

Group size: 1, Probability: 0.0000

Group size: 11, Probability: 0.1000

Group size: 21, Probability: 0.4114

Group size: 31, Probability: 0.7063

Group size: 41, Probability: 0.8925

Group size: 51, Probability: 0.9704

Group size: 61, Probability: 0.9945

Group size: 71, Probability: 0.9992

Group size: 81, Probability: 0.9999

Group size: 91, Probability: 1.0000


10. Write program to test:

A)Given rela on is equivalence or not.

def is_reflexive(rela on, elements):

"""Check reflexivity property."""

for a in elements:

if (a, a) not in rela on:

return False

return True

def is_symmetric(rela on):

"""Check symmetry property."""

for (a, b) in rela on:

if (b, a) not in rela on:

return False

return True

def is_transi ve(rela on):

"""Check transi vity property."""

for (a, b) in rela on:

for (c, d) in rela on:

if b == c and (a, d) not in rela on:

return False

return True

def is_equivalence_rela on(rela on, elements):

"""Check if the given rela on is an equivalence rela on."""

return (is_reflexive(rela on, elements) and

is_symmetric(rela on) and

is_transi ve(rela on))


# Example usage

if __name__ == "__main__":

# Define a set of elements and a rela on

elements = {1, 2, 3} # You can change this set to test with other elements

rela on = {(1, 1), (2, 2), (3, 3), (1, 2), (2, 1)} # You can change this rela on to test

if is_equivalence_rela on(rela on, elements):

print("The given rela on is an equivalence rela on.")

else:

print("The given rela on is NOT an equivalence rela on.")

OUTPUT:

The given rela on is an equivalence rela on.

B) Given algebraic system is Abelian group or not.

def is_closed(group, opera on):

"""Check closure property."""

for a in group:

for b in group:

if opera on(a, b) not in group:

return False

return True

def is_associa ve(group, opera on):

"""Check associa vity property."""

for a in group:

for b in group:

for c in group:

if opera on(opera on(a, b), c) != opera on(a, opera on(b, c)):


return False

return True

def has_iden ty(group, opera on):

"""Check iden ty element property."""

for e in group:

if all(opera on(a, e) == a and opera on(e, a) == a for a in group):

return e

return None

def has_inverses(group, opera on, iden ty):

"""Check inverse element property."""

for a in group:

if not any(opera on(a, b) == iden ty and opera on(b, a) == iden ty for b in group):

return False

return True

def is_commuta ve(group, opera on):

"""Check commuta vity property."""

for a in group:

for b in group:

if opera on(a, b) != opera on(b, a):

return False

return True

def is_abelian_group(group, opera on):

"""Check if the given algebraic system is an Abelian group."""

if not is_closed(group, opera on):

return False

if not is_associa ve(group, opera on):

return False
iden ty = has_iden ty(group, opera on)

if iden ty is None:

return False

if not has_inverses(group, opera on, iden ty):

return False

if not is_commuta ve(group, opera on):

return False

return True

# Example usage

if __name__ == "__main__":

# Define a set (group) and an opera on (addi on modulo 5)

group = {0, 1, 2, 3, 4} # You can change this set to test with other elements

opera on = lambda a, b: (a + b) % 5 # Change this to define a different opera on

if is_abelian_group(group, opera on):

print("The given algebraic system is an Abelian group.")

else:

print("The given algebraic system is NOT an Abelian group.")

You might also like