nonlocal count stackDFS = [i] finish = set() while stackDFS: vertex = stackDFS.pop() if not vertex in exploredNodes: exploredNodes.add(vertex) if vertex in graph: stackDFS.extend(graph[vertex] - exploredNodes) finish.add(vertex) count += len(finish) for i in reversed(finishTimes): count = 0 if not i in exploredNodes: _DFS(i) countOfSCC.append(count) countOfSCC.sort(reverse=True) return countOfSCC if __name__ == "__main__": inputList = readAsListOfDict('_410e934e6553ac56409b2cb7096a44aa_SCC.txt', '\s+', 2, fieldDataList=[int, int]) writeSingleToFile( 'Problem4.txt', ','.join( [str(i) for i in getStronglyConnectedComponents(inputList)[0:5]]))
# Naive Implementation # inputDict= { value:1 for value in inputList} # # tSet={} # for value in inputDict.copy(): # print(value) # for t in range: # if t-value in inputDict: # tSet.add(t) # del inputDict[value] # # return len(tSet) inputList.sort() tSet = set() for value in inputList: lower = bisect.bisect_left(inputList, min(range) - value) upper = bisect.bisect_right(inputList, max(range) - value) tSet |= set([value + j for j in inputList[lower:upper]]) return len(tSet) if __name__ == "__main__": inputList = readAsList( '_6ec67df2804ff4b58ab21c12edcb21f8_algo1-programming_prob-2sum.txt', int) writeSingleToFile("Problem6a.txt", twoSum(inputList, range(-10000, 10000 + 1)))
first = inputList.pop(0) minHeap, maxHeap = [], [first] medianSum = first for incomingValue in inputList: if incomingValue < maxHeap[0]: heapq.heappush(minHeap, -incomingValue) else: heapq.heappush(maxHeap, incomingValue) while abs(len(minHeap) - len(maxHeap)) > 1: if len(minHeap) + 1 < len(maxHeap): heapq.heappush(minHeap, -heapq.heappop(maxHeap)) elif len(maxHeap) + 1 < len(minHeap): heapq.heappush(maxHeap, -heapq.heappop(minHeap)) if len(minHeap) < len(maxHeap): medianSum += maxHeap[0] else: medianSum += (-minHeap[0]) return medianSum if __name__ == "__main__": inputList = readAsList("_6ec67df2804ff4b58ab21c12edcb21f8_Median.txt", int) writeSingleToFile("Problem6b.txt", simulateMedianHeap(inputList) % 10000)
d = dict() for node in nodeList: d.update({node: int(node, 2)}) return d def maskClustering(nodeList, maxSpacing, bitCount): """Return the number of clusters formed when maxSpacing is achieved""" swapMasks = calculateMasks(bitCount, maxSpacing) labels = generateIntegerLabels(nodeList) UFObj = UnionFind([value for key, value in labels.items()]) for node in nodeList: currentLabel = labels[node] for mask in swapMasks: modNodeLabel = swapByMask(node, mask) if modNodeLabel in labels: UFObj.union(labels[modNodeLabel], currentLabel) return UFObj.uniqueLeaders() if __name__ == '__main__': inputList = readAsList( "_fe8d0202cd20a808db6a4d5d06be62f4_clustering_big.txt") nodeCount, bitCount = [int(value) for value in inputList.pop(0).split(' ')] inputList = [re.sub('\s+', '', string) for string in inputList] writeSingleToFile("Problem2b.txt", maskClustering(inputList, 3, bitCount))
if i == j and array[i][j] < 0: return inf #infinity signifies negative cycle return min(min(array, key=lambda v: min(v))) if __name__ == "__main__": inputListG1 = readAsListOfDict('_6ff856efca965e8774eb18584754fd65_g1.txt', '\s+', 3, ["tail", "head", "cost"], [int, int, int], 0, 1) vertexCountG1, edgeCountG1 = [ int(i) for i in inputListG1.pop(0).split(' ') ] inputListG2 = readAsListOfDict('_6ff856efca965e8774eb18584754fd65_g2.txt', '\s+', 3, ["tail", "head", "cost"], [int, int, int], 0, 1) vertexCountG2, edgeCountG2 = [ int(i) for i in inputListG2.pop(0).split(' ') ] inputListG3 = readAsListOfDict('_6ff856efca965e8774eb18584754fd65_g3.txt', '\s+', 3, ["tail", "head", "cost"], [int, int, int], 0, 1) vertexCountG3, edgeCountG3 = [ int(i) for i in inputListG3.pop(0).split(' ') ] writeSingleToFile( 'Problem4.txt', min(runFloydWarshallAlgorithm(vertexCountG1, edgeCountG1, inputListG1), runFloydWarshallAlgorithm(vertexCountG2, edgeCountG2, inputListG2), runFloydWarshallAlgorithm(vertexCountG3, edgeCountG3, inputListG3)))
deletedNodes[randomEdge[1]]=randomEdge[0] for key,value in deletedNodes.items(): if value == randomEdge[1]: deletedNodes[key]=randomEdge[0] for i,e in enumerate(edgesInGraph): temp = [e[0],e[1]] if e[0] in deletedNodes: temp[0]=deletedNodes[e[0]] if e[1] in deletedNodes: temp[1]=deletedNodes[e[1]] edgesInGraph[i] = (temp[0],temp[1]) edgesInGraph=list(filter(lambda v: v[0]!=v[1],edgesInGraph)) minCuts = min(minCuts,len(edgesInGraph)) return minCuts if __name__=='__main__': inputList = readAsListOfDict('_f370cd8b4d3482c940e4a57f489a200b_kargerMinCut.txt','\s+',2,["vertex","neighbours"]) vertexList=set([ int(item["vertex"]) for item in inputList]) edgeList = set([ (min(int(item["vertex"]),int(neighbour)),max(int(item["vertex"]),int(neighbour))) for item in inputList for neighbour in item["neighbours"].strip().split('\t') if int(item["vertex"]) != int( neighbour) ]) start = time.time() writeSingleToFile('Problem3.txt',countKargersMinimumCuts(vertexList,edgeList)) end=time.time() print(end-start)
"""return edgeList of 2-SAT problem""" inputList.pop(0) clauseList = [tuple(int(x) for x in line.split(' ')) for line in inputList] edgeList = list() for clause in clauseList: edgeList.append({0: -clause[0], 1: clause[1]}) edgeList.append({0: -clause[1], 1: clause[0]}) return edgeList if __name__ == "__main__": inputFiles = [ '_02c1945398be467219866ee1c3294d2d_2sat1.txt', '_02c1945398be467219866ee1c3294d2d_2sat2.txt', '_02c1945398be467219866ee1c3294d2d_2sat3.txt', '_02c1945398be467219866ee1c3294d2d_2sat4.txt', '_02c1945398be467219866ee1c3294d2d_2sat5.txt', '_02c1945398be467219866ee1c3294d2d_2sat6.txt' ] resultList = [ getStronglyConnectedComponents(return2SATEdgeList( readAsList(fileName))) for fileName in inputFiles ] writeSingleToFile( "Problem6.txt", "".join( ('1' if result else '0' for result in resultList)))
arr[start], arr[end] = swap(arr[start], arr[end]) else: pivot = arr[mid] arr[start], arr[mid] = swap(arr[start], arr[mid]) comparisons = end - start wall = start + 1 for index in range(start + 1, end + 1): if arr[index] < pivot: arr[index], arr[wall] = swap(arr[index], arr[wall]) wall += 1 arr[start], arr[wall - 1] = swap(arr[start], arr[wall - 1]) return _quick(arr, start, wall - 2, pivotMethod) + _quick( arr, wall, end, pivotMethod) + comparisons def quickSort(arr, pivotMethod): """Performs QuickSort on Array and return comparisons""" return _quick(arr, 0, len(arr) - 1, pivotMethod) if __name__ == "__main__": inputList = readAsList("_32387ba40b36359a38625cbb397eee65_QuickSort.txt", int) writeSingleToFile("Problem2a.txt", quickSort(list(inputList), PIVOT_FIRST)) writeSingleToFile("Problem2b.txt", quickSort(list(inputList), PIVOT_LAST)) writeSingleToFile("Problem2c.txt", quickSort(list(inputList), PIVOT_MEDIAN))
def kruskalClustering(edgeList, nodeCount, numberOfClusters): """Return cost of maximum spacing edge after kruskal clustering""" edgeList.sort(key=lambda v: v["cost"]) UFObj = UnionFind(list(range(1, nodeCount + 1))) while UFObj.uniqueLeaders() != numberOfClusters: edge = edgeList.pop(0) UFObj.union(edge["node1"], edge["node2"]) maxSpacingEdge = {} while edgeList: maxSpacingEdge = edgeList.pop(0) if (UFObj.find(maxSpacingEdge["node1"]) != UFObj.find( maxSpacingEdge["node2"])): break return maxSpacingEdge["cost"] if __name__ == '__main__': inputList = readAsListOfDict( "_fe8d0202cd20a808db6a4d5d06be62f4_clustering1.txt", '\s+', 3, ['node1', 'node2', 'cost'], [int, int, int], 0, 1) nodeCount = int(inputList.pop(0)) writeSingleToFile("Problem2a.txt", kruskalClustering(inputList, nodeCount, 4))
ADVICE: If you're not getting the correct answer, try debugging your algorithm using some small test cases. And then post them to the discussion forum! """ __author__ = 'Vinayak' from fileIO import readAsListOfDict,writeSingleToFile def calculateOptimalKnapsack(itemList, size, count): """Returns optimal value when items from itemList are scheduled on knapsack of size size""" # Sub-problems Array knapsackValues = [[0 for i in range(size+1)] for j in range(count)] for c in range(1,count): for s in range(size+1): if itemList[c]["weight"] > s: knapsackValues[c][s]=knapsackValues[c-1][s] else: knapsackValues[c][s] = max(knapsackValues[c-1][s],knapsackValues[c-1][s-itemList[c]["weight"]] + itemList[c]["value"]) return knapsackValues[count-1][size] if __name__=='__main__': inputList = readAsListOfDict("_6dfda29c18c77fd14511ba8964c2e265_knapsack1.txt",'\s+' ,2,['value','weight'],[int,int],0,1) knapsackSize, itemCount = [int(value) for value in inputList.pop(0).split(' ')] writeSingleToFile("Problem3a.txt",calculateOptimalKnapsack(inputList, knapsackSize, itemCount))
min_dist, curr_node = heapq.heappop(minHeap) indexHeap = {tup[1]: i for i, tup in enumerate(minHeap)} unexploredNodes.remove(curr_node) shortestPath[curr_node] = min_dist for edge in graph[curr_node]: if edge[0] in unexploredNodes: dist, node = minHeap[indexHeap[edge[0]]] minHeap[indexHeap[edge[0]]] = (min(dist, min_dist + edge[1]), edge[0]) heapq.heapify(minHeap) return shortestPath if __name__ == "__main__": inputList = readAsListOfDict( "_dcf1d02570e57d23ab526b1e33ba6f12_dijkstraData.txt", '\s+', 2, ["node", "neighbourStr"], [int, str]) graph = { details["node"]: [ tuple(int(x) for x in neighbourDetails.split(',')) for neighbourDetails in details["neighbourStr"].strip().split('\t') ] for details in inputList } shortestPaths = runDijkstra(graph, 1, list(range(1, 201))) # print(shortestPaths) writeSingleToFile( "Problem5.txt", ",".join([ str(shortestPaths[key]) for key in [7, 37, 59, 82, 99, 115, 133, 165, 188, 197] ]))
#!/usr/bin/env python """ For this problem, use the same data set as in the previous problem. Your task now is to run the greedy algorithm that schedules jobs (optimally) in decreasing order of the ratio (weight/length). In this algorithm, it does not matter how you break ties. You should report the sum of weighted completion times of the resulting schedule --- a positive integer --- in the box below. """ __author__ = 'Vinayak' from fileIO import readAsListOfDict,writeSingleToFile from itertools import accumulate def calculateWeightedCompleteTime(jobs): """Schedule jobs based on difference (weight - length) and return weighted total time.""" jobs.sort(key=lambda v:v['weight']/v['length'],reverse=True) finishTime = list(accumulate([0]+jobs,lambda s,v:s+v['length'])) weightedCompletedTime = sum((jobs[i]['weight']*finishTime[i+1] for i in range(len(jobs)))) return weightedCompletedTime if __name__=="__main__": jobList=readAsListOfDict('_642c2ce8f3abe387bdff636d708cdb26_jobs.txt','\s+', 2,['weight','length'],[int,int],1) writeSingleToFile("Problem1b.txt",calculateWeightedCompleteTime(jobList)) pass
# A[((0,),0)]=0 # for m in range(1,cityCount): # B = dict() # for subset in combinations(range(1,cityCount),m): # subset=tuple([0]+list(subset)) # for j in subset: # if j != 0: # listWithOutJ = list(subset) # listWithOutJ.remove(j) # B[(subset,j)] =min([ math.inf if k==0 and (tuple(listWithOutJ),k) not in A else A[(tuple( # listWithOutJ),k)] + adjMatrix[k][j] for k in list(subset) if k != j ]) # A=B.copy() # print(m) # return min([ A[(range(25),j)] + adjMatrix[j][0] for j in range(1,cityCount) ]) if __name__ == "__main__": inputList = readAsList("_f702b2a7b43c0d64707f7ab1b4394754_tsp.txt") # inputList = readAsList("test.txt") cityCount = int(inputList.pop(0)) cities = { i: tuple(float(point) for point in plotStr.split(' ')) for i, plotStr in enumerate(inputList) } # generate adjacency matrix adjMatrix = [[euclidean(i, j) for j in range(cityCount)] for i in range(cityCount)] x = returnMinTSP(adjMatrix, cityCount) writeSingleToFile("Problem5.txt", math.floor(x)) print(math.floor(x), x)
heapq.heapify(edgeHeap) edge = heapq.heappop(edgeHeap) cost, node1, node2 = edge[0], edge[1][0], edge[1][1] if node1 not in exploredNodes: exploredNodes.add(node1) unexploredNodes.remove(node1) if node2 not in exploredNodes: exploredNodes.add(node2) unexploredNodes.remove(node2) MSTCost += cost edgesInMST.add((node1, node2, cost)) edgeList = list( filter( lambda e: e[1][0] in unexploredNodes or e[1][1] in unexploredNodes, edgeList)) return edgesInMST, MSTCost if __name__ == "__main__": inputList = readAsListOfDict('_d4f3531eac1d289525141e95a2fea52f_edges.txt', '\s+', 3, ['node1', 'node2', 'cost'], [int, int, int], 0, 1) nodeCount, edgeCount = [int(i) for i in inputList[0].split(' ')] del inputList[0] writeSingleToFile("Problem1c.txt", prim(inputList, nodeCount)[1])
elif arr[i] > arr[j]: ret.append(arr[j]) inversions += (m - i + 1) j += 1 for i in range(len(ret)): arr[start + i] = ret[i] return inversions def _mergeInversionCount(arr, start, end): """MergeSort while counting inversions""" if start >= end: return 0 else: m = (start + end) // 2 return _mergeInversionCount(arr, start, m) + _mergeInversionCount( arr, m + 1, end) + _merge(arr, start, end) def countInversions(arr): """Count no. of inversions""" return _mergeInversionCount(arr, 0, len(arr) - 1) if __name__ == "__main__": inputList = readAsList( "_bcb5c6658381416d19b01bfc1d3993b5_IntegerArray.txt", int) writeSingleToFile("Problem1.txt", countInversions(inputList)) pass