The document contains source code for solving various problems using greedy and dynamic programming algorithms. These include the 0/1 knapsack problem, all pairs shortest paths using Floyd-Warshall algorithm, finding good pairs of strings in binary strings, knapsack problem using greedy method, Dijkstra's algorithm for single source shortest path, and finding beautiful numbers using a greedy approach. The code includes functions, inputs, outputs, and explanations for each algorithmic problem solved.
Introduction to Casting Processes in Manufacturing
Exp.docx
1. Exp. No.: 06
0/1 KNAPSACK PROBLEM USING DYNAMIC PROGRAMMING
SOURCE CODE:
defknapsack(weights,values,capacity):
n=len(weights)
# Initialize a table to store the maximum values for different subproblems.
dp=[[0for_inrange(capacity+1)]for_inrange(n+1)]
# Build the table using dynamic programming.
foriinrange(1,n+1):
forwinrange(1,capacity+1):
ifweights[i-1]<=w:
# If the current item can fit in the knapsack, decide whether to
include it or not.
dp[i][w]=max(dp[i-1][w],dp[i-1][w-weights[i-1]]+
values[i-1])
else:
# If the current item's weight exceeds the current knapsack
capacity, skip it.
dp[i][w]=dp[i-1][w]
# Reconstruct the solution by backtracking through the table.
selected_items=[]
i,w=n,capacity
whilei>0andw>0:
ifdp[i][w]!=dp[i-1][w]:
selected_items.append(i-1)
w-=weights[i-1]
i-=1
# Return the maximum value and the indices of selected items.
max_value=dp[n][capacity]
returnmax_value,selected_items
# Take user input for weights, values, and capacity.
2. n=int(input("Enter the number of items: "))
weights=[]
values=[]
foriinrange(n):
weight=int(input(f"Enter the weight of item{i+1}: "))
value=int(input(f"Enter the value of item{i+1}: "))
weights.append(weight)
values.append(value)
capacity=int(input("Enter the knapsack capacity: "))
# Call the knapsack function with user-provided inputs.
max_value,selected_items=knapsack(weights,values,capacity)
print("Maximum value:",max_value)
print("Selected items:",selected_items)
OUTPUT:
Enter the number ofitems:5
Enter theweightof item1:2
Enter thevalueof item1:3
Enter theweightof item2:3
Enter thevalueof item2:4
Enter theweightof item3:4
Enter thevalueof item3:5
Enter theweightof item4:5
Enter thevalueof item4:6
Enter theweightof item5:6
Enter thevalueof item5:7
Enter theknapsackcapacity:7
Maximumvalue:9
Selecteditems: [2,1]
Exp. No.: 07
ALL-PAIRS SHORTEST PATHS USING FLOYDWARSHALL ALGORITHM
4. Shortest distances betweenallpairs ofvertices:
0356
5023
3601
2570
Exp. No.: 08
FIND & DISPLAY GOOD PAIRS OF STRING IN N BINARY STRINGS
SOURCE CODE:
deffind_common_characters(str1,str2):
# Create two sets to store the characters in each string
set1=set(str1)
set2=set(str2)
# Check if there's any common character
common_characters=set1.intersection(set2)
returncommon_characters
deffind_good_pairs(binary_strings):
good_pairs=[]
n=len(binary_strings)
foriinrange(n):
forjinrange(i+1,n):
common_chars=find_common_characters(binary_strings[i],
binary_strings[j])
iflen(common_chars)>0:
good_pairs.append((binary_strings[i],binary_strings[j]))
returngood_pairs
binary_strings=["1","01","001","000","11111","1010","101010"]
good_pairs=find_good_pairs(binary_strings)
forpairingood_pairs:
print(f"Good pair:{pair[0]}and{pair[1]}")
OUTPUT:
5. 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
Exp. No.: 09
KNAPSACK PROBLEM USING GREEDY METHOD
SOURCE CODE:
defknapsack_greedy(values,weights,capacity):
# Calculate the value-to-weight ratio for each item
value_per_weight=[(v/w,v,w)forv,winzip(values,weights)]
value_per_weight.sort(reverse=False)
total_value=0
knapsack=[]# Items selected for the knapsack
forratio,value,weightinvalue_per_weight:
6. ifcapacity>=weight:
knapsack.append((value,weight))
total_value+=value
capacity-=weight
returntotal_value,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
max_value,selected_items=knapsack_greedy(values,weights,capacity)
print(f"Maximum value:{max_value}")
print("Selected items:")
forvalue,weightinselected_items:
print(f"Value:{value}, Weight:{weight}")
OUTPUT:
Maximum value: 650
Selected items:
Value: 100, Weight: 20
Value: 400, Weight: 40
Value: 150, Weight: 10
Exp. No.: 10
DIJKSTRA’S ALGORITHM FOR SOLVING SINGLE SOURCE SHORTEST PATH PROBLEM USING GREEDY
APPROACH
SOURCE CODE:
importheapq
defdijkstra(graph,start):
# Create a dictionary to store the shortest distances from the start node
7. shortest_distances={node:float('inf')fornodeingraph}
shortest_distances[start]=0
# Create a priority queue to keep track of nodes to visit next
priority_queue=[(0,start)]
whilepriority_queue:
current_distance,current_node=heapq.heappop(priority_queue)
# If the current distance is greater than what we have in the dictionary,
skip this node
ifcurrent_distance>shortest_distances[current_node]:
continue
forneighbor,weightingraph[current_node].items():
distance=current_distance+weight
# If we find a shorter path to the neighbor, update the distance and add
it to the priority queue
ifdistance<shortest_distances[neighbor]:
shortest_distances[neighbor]=distance
heapq.heappush(priority_queue, (distance,neighbor))
returnshortest_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)
fornode,distanceinshortest_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
8. Shortest distance from A to C is 3
Shortest distance from A to D is 4
Exp. No.: 11
FIND BEAUTIFUL NUMBERS USING GREEDY APPROACH
SOURCE CODE:
defis_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:])
returnsum(map(int,str(first_half)))==sum(map(int,str(second_half)))
deffind_beautiful_numbers_in_interval(M,N):
beautiful_numbers=[]
fornuminrange(M,N+1):
ifis_beautiful_number(num):
beautiful_numbers.append(num)
returnbeautiful_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]