Loading...
More Python Posts
# Python program for implementation of Selection# Sortimport sysA = [64, 25, 12, 22, 11]# Traverse through all array elementsfor i in range(len(A)):# Find the minimum element in remaining# unsorted arraymin_idx = ifor j in range(i+1, len(A)):if A[min_idx] > A[j]:min_idx = j# Swap the found minimum element with# the first elementA[i], A[min_idx] = A[min_idx], A[i]# Driver code to test aboveprint ("Sorted array")for i in range(len(A)):print("%d" %A[i]),
# Python binary search functiondef binary_search(arr, target):left = 0right = len(arr) - 1while left <= right:mid = (left + right) // 2if arr[mid] == target:return midelif arr[mid] < target:left = mid + 1else:right = mid - 1return -1# Usagearr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]target = 7result = binary_search(arr, target)if result != -1:print(f"Element is present at index {result}")else:print("Element is not present in array")
def max_n(lst, n = 1):return sorted(lst, reverse = True)[:n]max_n([1, 2, 3]) # [3]max_n([1, 2, 3], 2) # [3, 2]
def calculate_values():value1 = 10value2 = 20return value1, value2result1, result2 = calculate_values()print("Result 1:", result1)print("Result 2:", result2)
import pandas as pdx = pd.read_excel(FILE_NAME)print(x)
#Python program to print topological sorting of a DAGfrom collections import defaultdict#Class to represent a graphclass Graph:def __init__(self,vertices):self.graph = defaultdict(list) #dictionary containing adjacency Listself.V = vertices #No. of vertices# function to add an edge to graphdef addEdge(self,u,v):self.graph[u].append(v)# A recursive function used by topologicalSortdef topologicalSortUtil(self,v,visited,stack):# Mark the current node as visited.visited[v] = True# Recur for all the vertices adjacent to this vertexfor i in self.graph[v]:if visited[i] == False:self.topologicalSortUtil(i,visited,stack)# Push current vertex to stack which stores resultstack.insert(0,v)# The function to do Topological Sort. It uses recursive# topologicalSortUtil()def topologicalSort(self):# Mark all the vertices as not visitedvisited = [False]*self.Vstack =[]# Call the recursive helper function to store Topological# Sort starting from all vertices one by onefor i in range(self.V):if visited[i] == False:self.topologicalSortUtil(i,visited,stack)# Print contents of stackprint(stack)g= Graph(6)g.addEdge(5, 2);g.addEdge(5, 0);g.addEdge(4, 0);g.addEdge(4, 1);g.addEdge(2, 3);g.addEdge(3, 1);print("Following is a Topological Sort of the given graph")g.topologicalSort()