Advance Programming Lab
Advance Programming Lab
:
Date:
Exp. No: 01
def max_subset_sum(arr):
n = len(arr)
max_sum = 0
max_sum_arr = 0
max_subset_size = 0
max_subset = []
for i in range(n):
current_sum = 0
current_subset = []
max_sum_arr += arr[i]
if __name__ == '__main__':
A = list(map(int, input().split()))
max_sum, max_subset_size, max_subset, max_sum_arr = max_subset_sum(A)
print('Array is:', A)
print('Max sum of arr:', max_sum_arr)
print('No. of elements in the chosen subset:', max_subset_size)
print('Chosen subset:', max_subset)
print('Maximum choosen subset sum:', max_sum)
OUTPUT:
1 2 4 -1 0 -3
Array is: [1, 2, 4, -1, 0, -3]
Max sum of arr: 3
No. of elements in the chosen subset: 3
Chosen subset: [1, 2, 4]
Maximum choosen subset sum: 7
group_capacities.sort()
plane_capacities.sort()
start = 0
end = num_planes
minimum_allocation_times = -1
QUICK SORT TECHNIQUE TO FIND AN INTEGER NOT IN THE ARRAY AND GREATER THAN KEY
SOURCE CODE:
def partition(array, low, high):
pivot = array[high]
i = low - 1
# data = [8, 7, 2, 1, 0, 9, 6]
data = list(map(int,input('Enter the array:').split()))
print('Unsorted Array:', data)
quickSort(data, 0, len(data) - 1)
sorted_array = data
print('Sorted Array:', sorted_array)
# key = 1
key = int(input('Enter the key : '))
def mergeSort(array):
if len(array) > 1:
mid = len(array) // 2
l = array[:mid]
r = array[mid:]
i=j=k=0
while i<len(l):
array[k] = l[i]
i += 1
k += 1
while j<len(r):
array[k] = r[j]
j += 1
k += 1
def measureTime(n):
array = [random.randint(1, 100000) for _ in range(n)]
start = timeit.default_timer()
mergeSort(array)
end = timeit.default_timer()
return end-start
# main program
if __name__ == '__main__':
n_values = [2000, 3000, 7000, 5000, 6000, 10000]
time_taken = []
for n in n_values:
time_taken.append(measureTime(n))
Roll No.: 21121A3359
SREE VIDYANIKETHAN ENGINEERING COLLEGE Page No.:
Date:
def printComplexity(n):
print('\nn_values\t Best_case \t Avg_case \t\t Worst_case')
for n in n_values:
best = n*math.log(n)
avg = n*math.log(n)
worst = n*math.log(n)
print(n,'\t', best,'\t', avg, '\t', worst)
printComplexity(n)
OUTPUT:
def find_max_passing_students():
N = int(input("Enter the number of students: "))
marks = []
bounds = []
for i in range(N):
student_marks = int(input(f"Enter marks for student {i+1}: "))
student_bound = int(input(f"Enter bound for student {i+1}: "))
marks.append(student_marks)
bounds.append(student_bound)
# Iterate through the students and calculate passing students using dynamic
programming
for i in range(1, N + 1):
for j in range(1, sum(marks) + 1):
student_marks, student_bound = students[i - 1]
if student_marks > j:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - student_marks] +
student_bound)
max_passing_students = find_max_passing_students()
print(f"The maximum number of students that can pass is: {max_passing_students}")
Maximum value: 9
Selected items: [2, 1]
import sys
def floyd_warshall(graph, num_vertices):
distance = graph
# Apply the Floyd-Warshall algorithm
for k in range(num_vertices):
for i in range(num_vertices):
for j in range(num_vertices):
if distance[i][k] + distance[k][j] < distance[i][j]:
distance[i][j] = distance[i][k] + distance[k][j]
return distance
if __name__ == "__main__":
graph = [
[0, 3, float("inf"), 7],
[8, 0, 2, float("inf")],
[5, float("inf"), 0, 1],
[2, float("inf"), float("inf"), 0]
]
num_vertices = len(graph)
OUTPUT:
def find_good_pairs(binary_strings):
good_pairs = []
n = len(binary_strings)
for i in range(n):
for j in range(i + 1, n):
common_chars = find_common_characters(binary_strings[i],
binary_strings[j])
if len(common_chars) > 0:
good_pairs.append((binary_strings[i], binary_strings[j]))
return good_pairs
OUTPUT:
Good pair: 1 and 01
Good pair: 1 and 001
Good pair: 1 and 11111
Good pair: 1 and 1010
Good pair: 1 and 101010
Good pair: 01 and 001
Good pair: 01 and 000
Good pair: 01 and 11111
Good pair: 01 and 1010
Good pair: 01 and 101010
Good pair: 001 and 000
Good pair: 001 and 11111
Good pair: 001 and 1010
Good pair: 001 and 101010
Good pair: 000 and 1010
Good pair: 000 and 101010
Good pair: 11111 and 1010
Good pair: 11111 and 101010
Good pair: 1010 and 101010
value_per_weight.sort(reverse=False)
total_value = 0
knapsack = [] # Items selected for the knapsack
# Example usage
# values = [60, 100, 120]
# weights = [10, 20, 30]
# capacity = 50
values = [100,500,400,150]
weights = [20,30,40,10]
capacity = 75
OUTPUT:
Maximum value: 650
Selected items:
Value: 100, Weight: 20
Value: 400, Weight: 40
Value: 150, Weight: 10
import heapq
def dijkstra(graph, start):
# Create a dictionary to store the shortest distances from the start node
shortest_distances = {node: float('inf') for node in graph}
shortest_distances[start] = 0
# Create a priority queue to keep track of nodes to visit next
priority_queue = [(0, start)]
while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)
# If we find a shorter path to the neighbor, update the distance and add
it to the priority queue
if distance < shortest_distances[neighbor]:
shortest_distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
return shortest_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}
}
start_node = 'A'
shortest_distances = dijkstra(graph, start_node)
for node, distance in shortest_distances.items():
print(f"Shortest distance from {start_node} to {node} is {distance}")
OUTPUT:
Shortest distance from A to A is 0
Shortest distance from A to B is 1
Shortest distance from A to C is 3
Shortest distance from A to D is 4
def is_beautiful_number(num):
num_str = str(num)
length = len(num_str)
N = length // 2
first_half = int(num_str[:N])
second_half = int(num_str[N:])
return beautiful_numbers
M = 10
N = 100
beautiful_numbers = find_beautiful_numbers_in_interval(M, N)
print("Beautiful numbers in the interval [", M, "-", N, "]:", beautiful_numbers)
OUTPUT:
Beautiful numbers in the interval [ 10 - 100 ]: [11, 22, 33, 44, 55, 66, 77, 88, 99]
solutions = []
backtrack(0, [], 0)
return solutions
S = [1, 2, 5, 6, 8]
d = 9
result = subset_sum(S, d)
if result:
print("Solutions:")
for subset in result:
print(subset)
else:
print("No solution found.")
OUTPUT:
Solutions:
[1, 2, 6]
[1, 8]
OUTPUT:
Exp. No.: 04
WORKING WITH DIFFERENT DATA FORMATS USING PANDAS
SOURCE CODE:
import pandas as pd
import json
from io import StringIO
def a():
csv_file_path = input("Enter the CSV file path: ")
df = pd.read_csv(csv_file_path)
print(df.head())
output_csv_path = input("Enter the output CSV file path: ")
df.to_csv(output_csv_path, index=False)
def b():
json_file_path = input("Enter the JSON file path: ")
df = pd.read_json(json_file_path)
print(df.head())
output_json_path = input("Enter the output JSON file path: ")
df.to_json(output_json_path, orient='records')
json_data = input("Enter JSON data as a string: ")
parsed_data = pd.read_json(StringIO(json_data))
print(parsed_data)
def c():
excel_file_path = input("Enter the Excel file path: ")
df = pd.read_excel(excel_file_path, sheet_name='Sheet1')
print(df.head())
output_excel_path = input("Enter the output Excel file path: ")
df.to_excel(output_excel_path, sheet_name='Sheet1', index=False)
def switch(ch):
if ch=='a':
return a()
elif ch=='b':
return b()
else:
return c()
t=1
while(t>0):
ch=input("Enter your choice:")
if ch=='e':
OUTPUT:
Enter your choice:a
Enter the CSV file path: your_input.csv
Name Age City
0 lakshmi 20 Kurnool
1 Ram 21 Chennai
2 marry 27 Mumbai
3 chalapathi 29 Tirupati
Enter the output CSV file path: output.csv
Enter your choice:b
Enter the JSON file path: your_input.json
name age city
0 latha 24 Chicago
1 somu 20 Mumbai
2 David 25 Tirupati
3 lucky 24 vizag
Enter the output JSON file path: output.json
Enter JSON data as a string: [{"name": "kiran", "age": 28, "city": "chennai"},
{"name": "lucky", "age": 26, "city": "vizag"}]
name age city
0 kiran 28 chennai
1 lucky 26 vizag
Enter your choice:c
Enter the Excel file path: your_input.xlsx
Unnamed: 0 Name Age City
0 1 John 30 vizag
1 2 Hari 25 chennai
2 3 Muni 28 mumbai
3 4 Marry 22 Tirupati
Enter the output Excel file path: output.xlsx
Enter your choice:e