JAVA PROGRAMS
JAVA PROGRAMS
Here’s a curated and efficient set of Python programs for all the listed topics. Due
to the large number of problems, I’ll provide them in batches, ensuring optimal
solutions for each. Here you go 🕺
if num < 0:
print("Factorial does not exist for negative numbers")
else:
for i in range(1, num + 1):
factorial *= i
print(f"Factorial of {num} is {factorial}")
if num == sum_of_powers:
print(f"{num} is an Armstrong number")
else:
print(f"{num} is not an Armstrong number")
try:
inverse = np.linalg.inv(matrix_np)
print("Inverse of the Matrix:")
print(inverse)
except np.linalg.LinAlgError:
print("Matrix is singular and cannot be inverted")
print("Sorted Words:")
print(" ".join(words))
count = string.count(substring)
print(f"The substring '{substring}' occurred {count} time(s) in the
string.")
lst.append(element)
print(f"Updated List: {lst}")
if lst1 == lst2:
print("The lists are equal")
else:
print("The lists are not equal")
if element in lst:
lst.remove(element)
print(f"Updated List: {lst}")
else:
print("Element not found in the list")
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
lst[k] = L[i]
i += 1
else:
lst[k] = R[j]
j += 1
k += 1
while queue:
(cost, vertex) = heapq.heappop(queue)
return distances
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)]
}
while edges:
weight, frm, to = heapq.heappop(edges)
if to not in visited:
visited.add(to)
mst.append((frm, to, weight))
return mst
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)]
}
for w, u, v in edges:
if disjoint_set.find(u) != disjoint_set.find(v):
disjoint_set.union(u, v)
mst.append((u, v, w))
return mst
graph = {
0: [(1, 1), (2, 4)],
1: [(0, 1), (2, 2), (3, 5)],
2: [(0, 4), (1, 2), (3, 1)],
3: [(1, 5), (2, 1)]
}
mst = kruskal(graph, 4)
print(f"Minimum Spanning Tree: {mst}")
Python Program to Solve the Fractional Knapsack Problem Using
Greedy Approach
def fractional_knapsack(weights, values, capacity):
n = len(weights)
ratio = [(values[i] / weights[i], weights[i], values[i]) for i in
range(n)]
ratio.sort(reverse=True, key=lambda x: x[0])
total_value = 0
for r, w, v in ratio:
if capacity >= w:
capacity -= w
total_value += v
else:
total_value += (capacity / w) * v
break
return total_value
def n_queens(n):
board = [-1] * n
if not solve_n_queens(board, 0, n):
print("Solution does not exist")
else:
print("Solution found")
Enjoy bro.! 😎