minimum insertions to form a palindrome
Brute-force approach Here I present a few approaches to deduce “minimum insertions” required to convert a string into a palindrome.
The basic brute force approach is quite simple, given a string with length L, start comparing, the first character from left and the last character while scanning inwards.
Here is a basic test for a palindrome.
L = len(s) for i in range(L): if s[i] != s[L - i - 1]: return False,i,L-i -1 return True,0,0 The above code returns True if the string is a palindrome or returns False with mismatching indices.
print two-dimensional array in spiral order
So I saw this problem in a book today about printing a 2d matrix in spiral order
Here are two solutions to it
Solution one. def printSpiralTL(m,x1,y1,x2,y2): for i in range(x1,x2): print m[y1][i] for j in range(y1+1,y2+1): print m[j][x2-1] if x2-x1 > 0: printSpiralBL(m, x1, y1 + 1, x2-1, y2) def printSpiralBL(m,x1,y1,x2,y2): for i in range(x2-1,x1-1,-1): print m[y2][i] for j in range(y2-1,y1-1,-1): print m[j][x1] if x2-x1 > 0: printSpiralTL(m, x1+1, y1, x2, y2-1) m = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 1] ] Output:
merge two sorted arrays in python
Here is a quick code snippet to merge two sorted arrays in python
merged = [] l = 0 r = 0 for i in range(len(a)+len(b) ): lval = None rval = None if l < len(a): lval = a[l] if r < len(b): rval = b[r] if (lval < rval and rval and lval) or rval == None: merged.append(lval) l+=1 elif (lval >= rval and rval and lval)or lval == None: merged.