Solution: Connecting n Pipes With Minimum Cost
This review provides a detailed analysis of how to connect n pipes with the minimum cost.
We'll cover the following...
Solution: sorting
import heapqdef min_cost(pipes):"""Calculates the minimum cost of connecting pipes:param pipes: A list where its length is the number of pipes and indexes are the specific lengths of the pipes.:return: The minimum cost"""# Create a priority queue out of the# given listheapq.heapify(pipes)# Initializ resultcost = 0# While size of priority queue# is more than 1while(len(pipes) > 1):# Extract shortest two pipes from the priority queuefirst = heapq.heappop(pipes)second = heapq.heappop(pipes)# Connect the pipe: update cost# and insert the new pipe to pipes queuecost += first + secondheapq.heappush(pipes, first + second)return cost# Main program to test above functionif __name__ == "__main__":pipes = [4, 3, 2, 6]print(min_cost(pipes))
Explanation
If you look at the ...
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy