DAA_1_ASS_redesigned
DAA_1_ASS_redesigned
1. Develop a program to print all the prime numbers in a given range using sieve of
Eratosthenes algorithm and find its time complexity.
CODE:
def sieve_of_eratosthenes(n):
primes = [True] * (n + 1)
if primes[i]:
primes[j] = False
if __name__ == "__main__":
primes = sieve_of_eratosthenes(n)
OUTPUT:
2. Develop a program to find the GCD of two numbers using Euclid’s algorithm.
CODE:
DEEPAN S 23CSEC39
while b:
a, b = b, a % b
return a
if __name__ == "__main__":
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(f"GCD of {a} and {b} is {gcd(a, b)}")
print("Time Complexity for GCD: O(log min(a, b))")
OUTPUT:
3. Implement a program to determine if all elements in a given array are unique. The
program should check if there are no duplicate elements in the array.
CODE:
def all_unique(arr):
return len(arr) == len(set(arr))
if __name__ == "__main__":
arr = list(map(int, input("Enter elements separated by space: ").split()))
print("All elements are unique:" if all_unique(arr) else "Duplicates found")
OUTPUT:
CODE:
DEEPAN S 23CSEC39
def find_max(arr):
if not arr:
return None
return max(arr)
if __name__ == "__main__":
arr = list(map(int, input("Enter elements separated by space: ").split()))
max_element = find_max(arr)
print(f"Maximum element: {max_element}")
# Test cases
test_cases = [
([3, 1, 4, 1, 5, 9, 2, 6], 9),
([10, 20, 30, 40, 50], 50),
([-5, -1, -10, -3], -1),
([7], 7),
([], None)
]
for i, (test, expected) in enumerate(test_cases, 1):
result = find_max(test)
print(f"Test Case {i}: {'Pass' if result == expected else 'Fail'}")
# Time complexity analysis
OUTPUT:
DEEPAN S 23CSEC39
5. Implement a program to perform matrix multiplication. The program should check
whether matrix multiplication is possible and display the output accordingly.
CODE:
if __name__ == "__main__":
import numpy as np
rows_A, cols_A = map(int, input("Enter dimensions of first matrix (rows cols): ").split())
A = [list(map(int, input().split())) for _ in range(rows_A)]
if cols_A != rows_B:
print("Matrix multiplication not possible")
DEEPAN S 23CSEC39
else:
result = matrix_multiply(A, B)
print("Resultant Matrix:")
for row in result:
print(" ".join(map(str, row)))
print("Time Complexity: O(n^3) for general case, O(n^2.807) with Strassen's algorithm")
OUTPUT:
6. Write a program to find all occurrences of a given substring within a larger string
using a brute force approach. The program should print the starting index of each
occurrence. Provide the program, test cases, and an analysis of its time
complexity.
CODE:
if __name__ == "__main__":
DEEPAN S 23CSEC39
text = input("Enter the main text: ")
pattern = input("Enter the substring to find: ")
indices = find_substring_occurrences(text, pattern)
if indices:
print("Substring found at indices:", indices)
else:
print("Substring not found.")
# Test cases
test_cases = [
("abracadabra", "abra", [0, 7]),
("hello world, hello universe", "hello", [0, 13]),
("aaaaaa", "aa", [0, 1, 2, 3, 4]),
("abcdef", "xyz", []),
("abcabcabc", "abc", [0, 3, 6])
]
for i, (txt, pat, expected) in enumerate(test_cases, 1):
result = find_substring_occurrences(txt, pat)
print(f"Test Case {i}: {'Pass' if result == expected else 'Fail'}")
print("Time Complexity: O((n-m+1) * m), where n is the length of text and m is the length
of the pattern.")
OUTPUT:
7. Implement Knapsack problem using a brute force approach. The program should
DEEPAN S 23CSEC39
find the maximum value that can be obtained by selecting items with given
weights and values to fit in a knapsack of a given capacity. Provide the program,
test cases, and an analysis of its time complexity.
CODE:
if __name__ == "__main__":
n = int(input("Enter number of items: "))
weights = list(map(int, input("Enter weights separated by space: ").split()))
values = list(map(int, input("Enter values separated by space: ").split()))
capacity = int(input("Enter knapsack capacity: "))
# Test cases
test_cases = [
([2, 3, 4, 5], [3, 4, 5, 6], 5, 10),
([1, 2, 3], [10, 15, 40], 5, 55),
([5, 10, 20], [50, 60, 140], 15, 110),
DEEPAN S 23CSEC39
([1, 1, 1], [10, 20, 30], 2, 50),
([4, 2, 3], [10, 4, 7], 6, 14)
]
OUTPUT:
CODE:
import itertools
import string
DEEPAN S 23CSEC39
for length in range(1, max_length + 1):
for attempt in itertools.product(chars, repeat=length):
if "".join(attempt) == target:
return "".join(attempt)
return None
if __name__ == "__main__":
target_password = input("Enter the password to crack: ")
max_length = int(input("Enter the maximum length to try: "))
# Test cases
test_cases = [
("abc", 3, "abc"),
("A1B", 3, "A1B"),
("xyz9", 4, "xyz9"),
("1234", 3, None),
("Zz9", 5, "Zz9")
]
DEEPAN S 23CSEC39
print("Time Complexity: O(c^n), where c is the number of characters to try and n is the
password length.")
OUTPUT:
9. Implement Traveling Salesman Problem using brute force algorithm. The program
should take a list of cities and their coordinates as input and output the shortest
route and its total distance. Provide the program, test cases, and an analysis of
its time complexity.
CODE:
import itertools
import math
def traveling_salesman_brute_force(cities):
min_path = None
min_distance = float('inf')
for perm in itertools.permutations(cities[1:]):
path = [cities[0]] + list(perm) + [cities[0]]
total_distance = sum(distance(path[i], path[i+1]) for i in range(len(path) - 1))
if total_distance < min_distance:
min_distance = total_distance
DEEPAN S 23CSEC39
min_path = path
return min_path, min_distance
if __name__ == "__main__":
n = int(input("Enter number of cities: "))
cities = []
for i in range(n):
x, y = map(int, input(f"Enter coordinates of city {i+1} (x y): ").split())
cities.append((x, y))
path, distance = traveling_salesman_brute_force(cities)
print("Shortest path:", path)
print("Total distance:", distance)
# Test cases
test_cases = [
([(0, 0), (2, 2), (2, 0), (0, 2)], 8.0),
([(1, 1), (4, 4), (4, 1), (1, 4)], 12.0),
([(0, 0), (3, 4), (6, 0)], 12.0),
([(0, 0), (1, 1), (2, 2), (3, 3)], 6.83)
]
for i, (cities, expected) in enumerate(test_cases, 1):
_, result = traveling_salesman_brute_force(cities)
print(f"Test Case {i}: {'Pass' if round(result, 2) == expected else 'Fail'}")
OUTPUT:
DEEPAN S 23CSEC39
10. Given a cost matrix, where the element at cost[i][j] represents the cost of
assigning the i-th job to the j-th worker, develop a program to find the assignment
of jobs to workers such that the total cost is minimized using a brute force
approach.
CODE:
import itertools
def calculate_cost(cost_matrix, assignment):
return sum(cost_matrix[i][assignment[i]] for i in range(len(assignment))
def job_assignment_brute_force(cost_matrix):
n = len(cost_matrix)
workers = range(n)
min_cost = float('inf')
best_assignment = None
for perm in itertools.permutations(workers):
current_cost = calculate_cost(cost_matrix, perm)
if current_cost < min_cost:
min_cost = current_cost
best_assignment = perm
return best_assignment, min_cost
if __name__ == "__main__":
n = int(input("Enter number of jobs/workers: "))
cost_matrix = []
for i in range(n):
row = list(map(int, input(f"Enter costs for job {i+1} (space-separated): ").split()))
cost_matrix.append(row)
assignment, min_cost = job_assignment_brute_force(cost_matrix)
print("Optimal assignment:", assignment)
print("Minimum cost:", min_cost)
# Test cases
DEEPAN S 23CSEC39
test_cases = [
([[9, 2, 7], [6, 4, 3], [5, 8, 1]], 7),
([[4, 1], [2, 5]], 3),
([[10, 3, 8, 7], [5, 2, 6, 9], [1, 4, 7, 8], [9, 6, 3, 5]], 13)
]
for i, (matrix, expected) in enumerate(test_cases, 1):
_, result = job_assignment_brute_force(matrix)
print(f"Test Case {i}: {'Pass' if result == expected else 'Fail'}")
OUTPUT:
RUBRICS:
DEEPAN S 23CSEC39
DEEPAN S 23CSEC39
DEEPAN S 23CSEC39
DEEPAN S 23CSEC39