q = deque() q.append("a") where q: curr = q.popleft()
q.extendleft([1,2,3,4]) # give [4,3,2,1]
Sort
1
bisect.bisect(a, x, lo=0, hi=len(a))
Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a.
1 2
a = [1,2,3,4,5] ind = bisect.bisect(a, 0) # gives 0
defquicksort_recursive(a): iflen(a) == 0: return a p = len(a) // 2 l = [i for i in a if i < a[p]] m = [i for i in a if i == a[p]] r = [i for i in a if i > a[p]] return quicksort_recursive(l) + m + quicksort_recursive(r)
# r is the point where the array is divided into two subarrays r = len(array)//2 L = array[:r] M = array[r:]
# Sort the two halves mergeSort(L) mergeSort(M)
i = j = k = 0
# Until we reach either end of either L or M, pick larger among # elements L and M and place them in the correct position at A[p..r] while i < len(L) and j < len(M): if L[i] < M[j]: array[k] = L[i] i += 1 else: array[k] = M[j] j += 1 k += 1
# When we run out of elements in either L or M, # pick up the remaining elements and put in A[p..r] while i < len(L): array[k] = L[i] i += 1 k += 1
while j < len(M): array[k] = M[j] j += 1 k += 1
# Print the array defprintList(array): for i inrange(len(array)): print(array[i], end=" ") print()
# Driver program if __name__ == '__main__': array = [6, 5, 12, 10, 9, 1]
for step inrange(1, len(array)): key = array[step] j = step - 1 # Compare key with each element on the left of it until an element smaller than it is found # For descending order, change key<array[j] to key>array[j]. while j >= 0and key < array[j]: array[j + 1] = array[j] j = j - 1 # Place key at after the element just smaller than it. array[j + 1] = key
data = [9, 5, 1, 4, 3] insertionSort(data) print('Sorted Array in Ascending Order:') print(data)
defselectionSort(array, size): for step inrange(size): min_idx = step
for i inrange(step + 1, size): # to sort in descending order, change > to < in this line # select the minimum element in each loop if array[i] < array[min_idx]: min_idx = i # put min at the correct position (array[step], array[min_idx]) = (array[min_idx], array[step])
data = [-2, 45, 0, 11, -9] size = len(data) selectionSort(data, size) print('Sorted Array in Ascending Order:') print(data)