SlideShare a Scribd company logo
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.
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
SOURCE CODE:
importsys
deffloyd_warshall(graph,num_vertices):
distance=graph
# Apply the Floyd-Warshall algorithm
forkinrange(num_vertices):
foriinrange(num_vertices):
forjinrange(num_vertices):
ifdistance[i][k]+distance[k][j]<distance[i][j]:
distance[i][j]=distance[i][k]+distance[k][j]
returndistance
defprint_solution(distance,num_vertices):
foriinrange(num_vertices):
forjinrange(num_vertices):
ifdistance[i][j]==float("inf"):
print("inf",end="t")
else:
print(distance[i][j],end="t")
print()
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)
shortest_paths=floyd_warshall(graph,num_vertices)
print("Shortest distances between all pairs of vertices:")
print_solution(shortest_paths,num_vertices)
OUTPUT:
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:
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:
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
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
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]

More Related Content

Similar to Exp.docx

Dynamic Programming-Knapsack Problem
Dynamic Programming-Knapsack ProblemDynamic Programming-Knapsack Problem
Dynamic Programming-Knapsack ProblemAmrita Yadav
 
Knapsack problem and Memory Function
Knapsack problem and Memory FunctionKnapsack problem and Memory Function
Knapsack problem and Memory FunctionBarani Tharan
 
Presentation of knapsack
Presentation of knapsackPresentation of knapsack
Presentation of knapsackGaurav Dubey
 
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEMMrunal Patil
 

Similar to Exp.docx (8)

Prolog resume
Prolog resumeProlog resume
Prolog resume
 
Prolog resume
Prolog resumeProlog resume
Prolog resume
 
Prolog resume
Prolog resumeProlog resume
Prolog resume
 
Prolog resume
Prolog resumeProlog resume
Prolog resume
 
Dynamic Programming-Knapsack Problem
Dynamic Programming-Knapsack ProblemDynamic Programming-Knapsack Problem
Dynamic Programming-Knapsack Problem
 
Knapsack problem and Memory Function
Knapsack problem and Memory FunctionKnapsack problem and Memory Function
Knapsack problem and Memory Function
 
Presentation of knapsack
Presentation of knapsackPresentation of knapsack
Presentation of knapsack
 
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
0/1 DYNAMIC PROGRAMMING KNAPSACK PROBLEM
 

Recently uploaded

Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdfKamal Acharya
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdfKamal Acharya
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfPipe Restoration Solutions
 
Construction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxConstruction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxwendy cai
 
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringC Sai Kiran
 
2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edgePaco Orozco
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringC Sai Kiran
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdfKamal Acharya
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxMd. Shahidul Islam Prodhan
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdfAhmedHussein950959
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.PrashantGoswami42
 
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES  INTRODUCTION UNIT-IENERGY STORAGE DEVICES  INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES INTRODUCTION UNIT-IVigneshvaranMech
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsAtif Razi
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Aryaabh.arya
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationRobbie Edward Sayers
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopEmre Günaydın
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf884710SadaqatAli
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdfKamal Acharya
 
Introduction to Casting Processes in Manufacturing
Introduction to Casting Processes in ManufacturingIntroduction to Casting Processes in Manufacturing
Introduction to Casting Processes in Manufacturingssuser0811ec
 

Recently uploaded (20)

Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Construction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxConstruction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptx
 
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES  INTRODUCTION UNIT-IENERGY STORAGE DEVICES  INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering Workshop
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 
Introduction to Casting Processes in Manufacturing
Introduction to Casting Processes in ManufacturingIntroduction to Casting Processes in Manufacturing
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
  • 3. SOURCE CODE: importsys deffloyd_warshall(graph,num_vertices): distance=graph # Apply the Floyd-Warshall algorithm forkinrange(num_vertices): foriinrange(num_vertices): forjinrange(num_vertices): ifdistance[i][k]+distance[k][j]<distance[i][j]: distance[i][j]=distance[i][k]+distance[k][j] returndistance defprint_solution(distance,num_vertices): foriinrange(num_vertices): forjinrange(num_vertices): ifdistance[i][j]==float("inf"): print("inf",end="t") else: print(distance[i][j],end="t") print() 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) shortest_paths=floyd_warshall(graph,num_vertices) print("Shortest distances between all pairs of vertices:") print_solution(shortest_paths,num_vertices) OUTPUT:
  • 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]