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

DMP JS 4-9 Assignment

The document contains code and assignments related to discrete mathematics and Python from a university course. It includes code for determining if a list of pairs represents a function or relation, representing relations as matrices, propositional logic with truth tables, and equivalence and implication. The assignments cover topics like functions vs relations, matrix representation of relations, propositional logic, and equivalence and implication. The code includes functions to evaluate logical expressions, generate truth tables, get user input, and represent relations as matrices.

Uploaded by

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

DMP JS 4-9 Assignment

The document contains code and assignments related to discrete mathematics and Python from a university course. It includes code for determining if a list of pairs represents a function or relation, representing relations as matrices, propositional logic with truth tables, and equivalence and implication. The assignments cover topics like functions vs relations, matrix representation of relations, propositional logic, and equivalence and implication. The code includes functions to evaluate logical expressions, generate truth tables, get user input, and represent relations as matrices.

Uploaded by

Mivan mehta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

ITM (SLS) Baroda University

School of Computer Science, Engineering and Technology


Discrete Mathematics with Python
Sem - 1

Assignment – 4

Question :-

Write a Python function that takes a list of pairs as an argument and determines if the
argument constitutes a function or a general relation.

CODE (With user input) :-

def is_function_or_relation(pairs):
domain = set()
codomain = set()
seen_inputs = set()
for pair in pairs:
if len(pair) != 2:
return "Invalid pair format. Each pair should have exactly two elements."
input_value, output_value = pair
domain.add(input_value)
codomain.add(output_value)
if input_value in seen_inputs:
return "Not a function. Multiple outputs for the same input."
seen_inputs.add(input_value)
if len(domain) == len(codomain):
return "Function"
else:
return "General Relation"
def main():
pairs_str = input("Enter pairs as comma-separated values (e.g., 1,2 3,4): ")
pairs_list = [tuple(map(int, pair.split(','))) for pair in pairs_str.split()]
result = is_function_or_relation(pairs_list)
print(f"The entered pairs constitute a: {result}")
if __name__ == "__main__":
main()

Output :-

CODE (Without user input) :-

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

def is_function(pairs):
"""
Determines whether a list of pairs represents a function or a general relation.
Args:
pairs (list of pairs): A list of pairs representing the input-output pairs of the
relation.
Returns:
bool: True if the relation represents a function, False otherwise.
"""
input_values = set()
for pair in pairs:
input_value = pair[0]
if input_value in input_values:
return False
else:
input_values.add(input_value)
return True
pairs1 = [(1, 2), (2, 3), (3, 4)]
pairs2 = [(1, 2), (1, 3), (2, 4)]
is_function_result1 = is_function(pairs1)
is_function_result2 = is_function(pairs2)
print(f"Is the first relation a function? {is_function_result1}")
print(f"Is the second relation a function? {is_function_result2}")

Output :-

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

Assignment – 5

Question :-

Write a program to denote Relation: as subsets of a cartesian product of a set, matrix


representation.

CODE (With user input) :-

def get_user_input():
set_elements = input("Enter elements of the set separated by spaces: ").split()
set_elements = sorted(set(set_elements))
relation_size = int(input("Enter the size of the relation: "))
relation = []
for i in range(relation_size):
pair = input(f"Enter pair {i + 1} as comma-separated values (e.g., 1,2): ").split(',')
relation.append((pair[0], pair[1]))
return set_elements, relation
def create_matrix(set_elements, relation):
matrix_size = len(set_elements)
matrix = [[0] * matrix_size for _ in range(matrix_size)]
for pair in relation:
index1 = set_elements.index(pair[0])
index2 = set_elements.index(pair[1])
matrix[index1][index2] = 1
return matrix
def print_matrix(matrix, set_elements):
print("Matrix Representation:")
header = [" "] + list(set_elements)
print("\t".join(header))
for i, row in enumerate(matrix):
row_str = f"{list(set_elements)[i]}\t" + "\t".join(map(str, row))
print(row_str)
def main():
set_elements, relation = get_user_input()
matrix = create_matrix(set_elements, relation)
print_matrix(matrix, set_elements)
if __name__ == "__main__":
main()

Output :-

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

CODE (Without user input) :-

def relation_to_matrix(set_elements, relation):

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

matrix_size = len(set_elements)
matrix = [[0] * matrix_size for _ in range(matrix_size)]
for pair in relation:
index1 = set_elements.index(pair[0])
index2 = set_elements.index(pair[1])
matrix[index1][index2] = 1
return matrix
def print_matrix(matrix, set_elements):
print("Matrix Representation:")
header = [" "] + list(set_elements)
print("\t".join(header))
for i, row in enumerate(matrix):
row_str = f"{list(set_elements)[i]}\t" + "\t".join(map(str, row))
print(row_str)
def main():
set_elements = ['a', 'b', 'c']
relation = [('a', 'b'), ('b', 'c'), ('c', 'a')]
matrix = relation_to_matrix(set_elements, relation)
print_matrix(matrix, set_elements)
if __name__ == "__main__":
main()

Output :-

Assignment – 6
Question :-

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

Write a program for Propositional Logic, Logic operators, Truth Tables.

CODE (With user input) :-

import itertools
def evaluate_expression(expression, variable_values):
stack = []
for char in expression:
if char.isalpha():
stack.append(variable_values[char])
elif char == '¬':
operand = stack.pop()
stack.append(not operand)
elif char == '∧':
operand2 = stack.pop()
operand1 = stack.pop()
stack.append(operand1 and operand2)
elif char == '∨':
operand2 = stack.pop()
operand1 = stack.pop()
stack.append(operand1 or operand2)
return stack[0]
def generate_truth_table(variables):
values_combinations = list(itertools.product([False, True], repeat=len(variables)))
table_header = variables + ["Result"]
print("\t".join(table_header))
for values in values_combinations:
variable_values = dict(zip(variables, values))
result = evaluate_expression(expression, variable_values)
row_values = [str(value) for value in values] + [str(result)]
print("\t".join(row_values))
if __name__ == "__main__":
expression = input("Enter a propositional logic expression using ¬ (not), ∧ (and), ∨
(or): ")
variables = sorted(set(char for char in expression if char.isalpha()))
print("\nTruth Table:")
generate_truth_table(variables)

Output :-

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

CODE (Without user input) :-

import itertools
def evaluate_expression(expression, variable_values):
stack = []
for char in expression:
if char.isalpha():
stack.append(variable_values[char])
elif char == '¬':
operand = stack.pop()
stack.append(not operand)
elif char == 'and':
operand2 = stack.pop()
operand1 = stack.pop()
stack.append(operand1 and operand2)
elif char == 'or':
operand2 = stack.pop()
operand1 = stack.pop()
stack.append(operand1 or operand2)
return stack[0]
def generate_truth_table(variables, expression, max_rows=5):
values_combinations = list(itertools.product([False, True], repeat=len(variables)))
table_header = variables + [expression]
print("\t".join(table_header))
for i, values in enumerate(values_combinations):
if i >= max_rows:
print("...")
break
variable_values = dict(zip(variables, values))
result = evaluate_expression(expression, variable_values)
row_values = [str(value) for value in values] + [str(result)]

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

print("\t".join(row_values))
if __name__ == "__main__":
expression = "p and q or not r"
variables = sorted(set(char for char in expression if char.isalpha()))
print("\nPartial Truth Table:")
generate_truth_table(variables, expression, max_rows=5)

Output :-

Assignment – 7
Question :-

Write a program for Equivalence and implication.

CODE (With user input) :-

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

def is_equivalent(statement1, statement2):


return statement1 == statement2
def implies(statement1, statement2):
return not statement1 or statement2
def get_user_input():
statement1 = input("Enter the first logical statement (True or False): ").lower()
statement2 = input("Enter the second logical statement (True or False): ").lower()
if statement1 not in ['true', 'false'] or statement2 not in ['true', 'false']:
print("Invalid input. Please enter 'True' or 'False'.")
exit()
return statement1 == 'true', statement2 == 'true'
def main():
print("Logical Equivalence and Implication Evaluator")
statement1, statement2 = get_user_input()
equivalence_result = is_equivalent(statement1, statement2)
print(f"Equivalence Result: {equivalence_result}")
implication_result = implies(statement1, statement2)
print(f"Implication Result: {implication_result}")
if __name__ == "__main__":
main()

Output :-

CODE (Without user input) :-

def is_equivalent(statement1, statement2):


return statement1 == statement2
def implies(statement1, statement2):
return not statement1 or statement2
def main():
statement_a = True
statement_b = False

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

equivalence_result = is_equivalent(statement_a, statement_b)


print(f"Equivalence Result: {equivalence_result}")
implication_result = implies(statement_a, statement_b)
print(f"Implication Result: {implication_result}")
if __name__ == "__main__":
main()

Output :-

Assignment – 8
Question :-

Write a program for Functions: functional Python programming

CODE (With user input) :-

from functools import reduce


def get_user_input():
try:
numbers = input("Enter a list of numbers separated by spaces: ").split()

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

numbers = list(map(float, numbers))


return numbers
except ValueError:
print("Invalid input. Please enter valid numbers.")
return get_user_input()
def calculate_sum(numbers):
return reduce(lambda x, y: x + y, numbers)
def calculate_product(numbers):
return reduce(lambda x, y: x * y, numbers)
def main():
print("Functional Programming with User Input")
numbers = get_user_input()
total_sum = calculate_sum(numbers)
product = calculate_product(numbers)
print(f"List of Numbers: {numbers}")
print(f"Sum of Numbers: {total_sum}")
print(f"Product of Numbers: {product}")
if __name__ == "__main__":
main()

Output :-

CODE (Without user input) :-

from functools import reduce


def calculate_sum(numbers):
return reduce(lambda x, y: x + y, numbers)
def calculate_product(numbers):
return reduce(lambda x, y: x * y, numbers)
def main():
print("Functional Programming without User Input")
numbers = [1, 2, 3, 4, 5]
total_sum = calculate_sum(numbers)
product = calculate_product(numbers)
print(f"List of Numbers: {numbers}")
print(f"Sum of Numbers: {total_sum}")

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

print(f"Product of Numbers: {product}")


if __name__ == "__main__":
main()

Output :-

Assignment – 9
Question :-

Write a program for Recursion: functions, generators

CODE (With user input) (Chat Gpt):-

def fibonacci_generator(limit, a=0, b=1):


if a > limit:
return
yield a
yield from fibonacci_generator(limit, b, a + b)
def get_user_input():
try:

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

limit = int(input("Enter the limit for Fibonacci numbers: "))


return limit
except ValueError:
print("Invalid input. Please enter a valid integer.")
return get_user_input()
def main():
print("Fibonacci Generator with User Input")
limit = get_user_input()
print(f"Fibonacci numbers up to {limit}:")
for num in fibonacci_generator(limit):
print(num, end=" ")
if __name__ == "__main__":
main()

Output :-

CODE (Without user input) (Chat gpt):-

def fibonacci_generator(limit, a=0, b=1):


if a > limit:
return
yield a
yield from fibonacci_generator(limit, b, a + b)
def main():
print("Fibonacci Generator without User Input")
limit = 5
print(f"Fibonacci numbers up to {limit}:")
for num in fibonacci_generator(limit):
print(num, end=" ")
if __name__ == "__main__":
main()

Output :-

JAINAM SONI CLASS 3 (Btech CSE AI/DS)


ITM (SLS) Baroda University
School of Computer Science, Engineering and Technology
Discrete Mathematics with Python
Sem - 1

JAINAM SONI CLASS 3 (Btech CSE AI/DS)

You might also like