Posts

Showing posts from March, 2017

Insertion Sort

In this sorting algorithm, we check every element with it's previous element. If it is lesser than the previous element than we swap. We keeping swapping until the element achieves it's proper place. It's time complexity is O(n^2). In case the given list is already sorted, this algorithm works very fast. A simple code implementation is:- def insertionSort(l):   for i in range(len(l)):     pos=i     while(l[pos]>l[pos-1] and pos>0):       (l[pos],l[pos-1])=(l[pos-1],l[pos])       pos-=1   return l

Selection Sort

The following is the basic code of Selection Sort algorithm:- def selectionSort(l):   for i in range(len(l)):     minpos=i     for j in range(i,len(l)):       if l[j]<l[minpos]:         minpos=j     (l[i],l[minpos])=(l[minpos],l[i])           return l         

Sum of squares

Q.  A positive integer   n   is a sum of squares if   n = i 2  + j 2   for integers   i,j   such that   i ≥ 1   and   j ≥ 1 . For instance, 10 is a sum of squares because 10 = 1 2   + 3 2 , and so is 25 (3 2   + 4 2 ). On the other hand, 11 and 3 are not sums of squares. Write a Python function  sumofsquares(n)  that takes a positive integer argument and returns  True  if the integer is a sum of squares, and  False  otherwise. Ans- def sumofsquares(n):   (i,j)=(1,1)   for i in range(1,n):     for j in range(1,n):       if n == (i*i) + (j*j):         return (True)            return False   

Non-decreasing list (using recursion)

Q.  A list is a non-decreasing if each element is at least as big as the preceding one. For instance  [] ,  [7] ,  [8,8,11]  and  [3,19,44,44,63,89]  are non-decreasing, while  [3,18,4]  and  [23,14,3,14,3,23]  are not. Here is a recursive function to check if a list is non-decreasing. You have to fill in the missing argument for the recursive call. Ans- def nondecreasing(l):   if l==[] or len(l) == 1:     return(True)   else:     return( l[0] <= l[1] and nondecreasing(l[1:]))