.

Thursday, November 17, 2016

Creating dictionaries from two list/tuples

We have two lists/tuples of equal length and wan to create a dictionary from these two lists.



There are many ways but below I have stated three

1) Using dict constructor:


2) Using dict comprehensions:


3) Using itertools.izip for python versions < 3.0. if we choose to use previous 2 options for python 2.7 or other python versions less than 3.0, zip method will return a list which is not recommended when input lists are of big size as it will require more space and time. Instead we use itertools which return iterable object when used. for python 3 and higher zip has the same behavior as of izip


Let me know your suggestions and queries.




Thursday, August 4, 2016

Odd Occurrences In Array Algo and Implementation in Python

A non-empty zero-indexed array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9
  • the elements at indexes 0 and 2 have value 9,
  • the elements at indexes 1 and 3 have value 3,
  • the elements at indexes 4 and 6 have value 9,
  • the element at index 5 has value 7 and is unpaired.

XOR Operation :  It is a bit wise logical operation that only returns true if both the inputs are the same

Properties of XOR Here are several useful properties of XOR. This applies to plain XOR and bitwise XOR.
  • x (+) 0 = x  XORing with 0 gives you back the same number. Thus, 0 is the identity for XOR. x (+) 1 = \x  XORing with 1 gives you back the negation of the bit. Again, this comes from the truth table. For bitwise XOR, the property is slightly different: 
  • x ^ ~0 = ~x . That is, if you XOR with all 1's, the result will be the bitwise negation of x. 
  • x (+) x = 0  XORing x with itself gives you 0. That's because x is either 0 or 1, and 0 (+) 0 = 0 and 1 (+) 1 = 0. 
  • XOR is associative.That is: (x (+) y) (+) z = x (+) (y (+) z). You can verify this by using truth tables. 
  • XOR is commutative.That is: x (+) y = y (+) x.
 Implementation1: Using Bit wise XOR(^)

1
2
3
4
5
def solution(A):
    result = 0
    for number in A:
        result = result ^ number
    return result

Counter Collection : A Counter is a dict subclass for counting hashables objects. More details can be found in python documentation https://docs.python.org/3/library/collections.html#collections.Counter
 
Implementation2: Using Counter Collection
 
1
2
3
4
5
from collection import Counter
def solution(A):
    for i in Counter(A):
        if Counter(A)[i]%2 == 1:
            return i

Wednesday, August 3, 2016

CyclicRotation Algo and Implementation in Python

A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place.
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes.
Implementation 1: Without using any inbuilt functionality

1
2
3
4
5
6
def solution(A, K):
    result = []
    length = len(A)
    for i in range(length):
        result.insert((abs((i + K) % length)), A[i])
    return result 


Implementation 2: Using Deque data structure

1
2
3
4
5
6
from collections import deque

def solution(A, K):
    items = deque(A)
    items.rotate(K)
    return list(items)


Implementation 2: One Liner solution

1
2
def solution(A, K):
    return A[-K % len(A):] + A[:-K % len(A)]

BinaryGap Algo and implementation in Python

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
Implementation 1:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def solution(N):
    bin_list = []
    bin_gap = 0
    pre_gap = 0
    flag = False
    while(N > 0):
        if N % 2 == 0:
            bin_list.append(0)
        else:
            bin_list.append(1)
        N = N // 2
    for i in bin_list:
        if i == 1:
            flag = True
            if (bin_gap > pre_gap):
                pre_gap = bin_gap
            bin_gap = 0
        elif (i == 0 and flag is True):
            bin_gap += 1
        else:
            continue
    return pre_gap


Implementation 2:
 
1
2
def solution(N):
    return len(max((bin(N)[2:]).split('1' - 1), key=len))



Saturday, September 12, 2015

List of all unique pairs of prime factors of a number

import itertools

def primefactors(x):
    factorlist=[]
    loop=2
    while loop<=x:
        if x%loop==0:
            x/=loop
            factorlist.append(loop)
        else:
            loop+=1    return factorlist
x=input()

alist=primefactors(x)
for L in range(1, len(alist)+1):
         for subset in set(itertools.combinations(alist,L)):
            
            print(subset)


Console:

36
(2,)
(3,)
(2, 3)
(3, 3)
(2, 2)
(2, 2, 3)
(2, 3, 3)
(2, 2, 3, 3)

Wednesday, August 26, 2015

List of all files with particular extension in a directory

 

The method walk() generates the file names in a directory tree by walking the tree either top-down or bottom-up.

 fnmatch() compares a single file name against a pattern and returns a boolean indicating whether or not they match.

root  : Prints out directories only from what you specified  
dirs  : Prints out sub-directories from root.  
 files : Prints out all files from root and directories
  
 To get a full path (which begins with top) to a file or directory in dirpath, do 
os.path.join(dirpath, name).


_author__ = 'deepika'import fnmatch
import os

rootPath = 'D:\songs\\'pattern = '*.mp3'
for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
       print(os.path.join(root, filename) )

 ------------------------------------------

Output


D:\songs\English Songs\alladin - arabian night.mp3
D:\songs\English Songs\Axel f - Crazy Frog.mp3
D:\songs\English Songs\backstboys.mp3
D:\songs\English Songs\Black Eyed Peas- Dum Diddly.mp3
 

Saturday, August 15, 2015

Python program to find number of times each word is in the .txt file OR that finds most frequent word in a .txt file.

__author__ = 'kamal'
 import re
from collections import Counter
f=open('C:\Python27\myfile.txt', 'r')
passage = f.read()
words = re.findall(r'\w+', passage)
cap_words = [word.upper() for word in words]
# Converting to uppercase so that 'Is' & 'is' like words  should be considered as same words
word_counts = Counter(cap_words)
print(word_counts)











Output------------------------------------------------

Counter({'USED': 2, 'IN': 2, 'THE': 2, 'FREQUENT': 2, 'TO': 1, 'WORD': 1, 'MOST': 1, 'THIS': 1, 'OF': 1, 'IS': 1, 'NUMBER': 1, 'LEAST': 1, 'TIMES': 1, 'ALSO': 1, 'PROGRAM': 1, 'MANNER': 1, 'FILE': 1, 'EACH': 1, 'COUNTS': 1, 'SORTED': 1, 'HELLO': 1})

Process finished with exit code 0

Sunday, August 2, 2015

Quick Sort : using traditional partition concept.

Quicksort or partition-exchange sort, is a fast sorting algorithm, which is using divide and
 conquer algorithm. Quicksort first divides a large list into two smaller sub-lists:
 the low elements and the high elements. Quicksort can then recursively sort the sub-lists.

pivot -In the very early versions of quicksort, the leftmost element of the partition would often be chosen
 as the pivot element. Unfortunately, this causes worst-case behavior on already sorted arrays, which
 is a rather common use-case. The problem was easily solved by choosing either a random index for the pivot or choosing the middle index of the partition.

Average case performance‎: ‎O(n log n)
Best case performance‎      :  O(n log n)
Worst case performance‎    :  ‎O(n2)


Here i am taking middle element as pivot.

Steps to implement Quick sort:

1) Choose an element, called pivot, from the list. Generally pivot can be the middle index element.
2) Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values   greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final   position. This is called the partition operation.
3) Recursively apply the above steps to the sub-list of elements with smaller values and separately the sub-list of elements with greater values.


__author__ = 'deepika'

__author__ = 'deepika'

def quicksort(alist ,left ,right):
    if left >= right:
        return 

    partition = partitn(alist,left,right)
    if left < partition - 1:
        quicksort(alist, left, partition - 1)

    if partition < right:
        quicksort(alist, partition, right)
def partitn(alist, left, right):
    i=left
    j=right
    mid=(left+right)/2 

    pivot=alist[mid]
    while i <= j:
        while alist[i] < pivot:
            i=i+1 

        while alist[j] > pivot:
            j=j-1 

        if i <= j:
            temp = alist[i]
            alist[i] = alist[j]
            alist[j] = temp
            i = i + 1 

            j = j - 1 

   return i
alist = [9, 4, 3, 1, 6, 8, 2, 0]
left = 0

 right = len(alist)-1 

quicksort(alist,left,right)
print("----O-u-t-p-u-t-----")
print(alist)




----O-u-t-p-u-t-----
[0, 1, 2, 3, 4, 6, 8, 9]


1) Choose an element, called pivot, from the list. Generally pivot can be the middle index element.
2) Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
3) Recursively apply the above steps to the sub-list of elements with smaller values and separately the sub-list of elements with greater values.
Quick Sort
- See more at: http://www.java2novice.com/java-sorting-algorithms/quick-sort/#sthash.F34FiGUQ.dpuf
Steps to implement Quick sort:

1) Choose an element, called pivot, from the list. Generally pivot can be the middle index element.
2) Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
3) Recursively apply the above steps to the sub-list of elements with smaller values and separately the sub-list of elements with greater values.
Quick Sort
- See more at: http://www.java2novice.com/java-sorting-algorithms/quick-sort/#sthash.F34FiGUQ.dpuf
Quicksort or partition-exchange sort, is a fast sorting algorithm, which is using divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists. - See more at: http://www.java2novice.com/java-sorting-algorithms/quick-sort/#sthash.F34FiGUQ.dpuf
Quicksort or partition-exchange sort, is a fast sorting algorithm, which is using divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists. - See more at: http://www.java2novice.com/java-sorting-algorithms/quick-sort/#sthash.F34FiGUQ.dpuf
Quicksort or partition-exchange sort, is a fast sorting algorithm, which is using divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists. - See more at: http://www.java2novice.com/java-sorting-algorithms/quick-sort/#sthash.F34FiGUQ.dpuf
Quicksort or partition-exchange sort, is a fast sorting algorithm, which is using divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists. - See more at: http://www.java2novice.com/java-sorting-algorithms/quick-sort/#sthash.F34FiGUQ.dpuf
Quicksort or partition-exchange sort, is a fast sorting algorithm, which is using divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists. - See more at: http://www.java2novice.com/java-sorting-algorithms/quick-sort/#sthash.F34FiGUQ.dpuf

Data Structures 1: Python List/Arrays

As we have discussed 3 different sorting algorithms in the previous posts (Selection Sort , Bubble Sort, Insertion Sort ), you may have noticed that the input is stored as a sequence in square brackets[] and assigned to a variable. This notation is for creating list in Python. Lists or arrays are generally for storing a sequence of items of same data type. Lists are most basic data structure and comes in-built in most of the programming languages. Python list allows you to insert different data type items and hence made things easier.


Syntax


>>> fruits = ['Banana', 'Apple', 'Lime','Oranges','Grapes']


Operations Lists can be indexed,sliced,manipulated with other inbuilt functions. Below are shown some of the examples.


>>> print(fruits[1])
>>> print(fruits[1:3])
>>> fruits.append('Mango')

Pyhton code for QuickSort using Enumerate


The enumerate function adds an index so you can tell what the index of an item in your iterable is. The xrange function returns an iterable full of numbers. Use it when you want to do something a certain number of times, instead of for each element in an iterable.


__author__ = 'deepika'
def quick_sort(alist):

    if len(alist) > 1:
        pivot_index = len(alist) / 2
        smalleritems = []
        largeritems = []

        for i, val in enumerate(alist):
            if i != pivot_index:
                if val < alist[pivot_index]:
                    smalleritems.append(val)
                else:
                    largeritems.append(val)

        quick_sort(smalleritems)
        quick_sort(largeritems)
        alist[:] = smalleritems + [alist[pivot_index]] + largeritems



alist=[9,8,7,5,0,3]
quick_sort(alist)
print(alist)


Output-
[0, 3, 5, 7, 8, 9]

Wednesday, July 22, 2015

Selection Sort - using Python

Selection sort is also one of the basic sort algorithms and run in quadratic time O(n^2) same as Insertion sort.  The Selection sort is better than Insertion sort in terms of space complexity but has slower  than insertion sort in terms of time complexity.

Here we do not swap numbers after every comparison; rather we find the smallerst/largest numbers, save it in a temporary variable and replace it with the leftmost element in right array. In result we get sorted array on left hand side.

Explanation

Given an unsorted list the algorithm finds the smallest element and swap it with first element. Then it searches for smallest element in list excluding the 1st element  and so on till the list got sorted finally.



Below are the differences between Selection sort and Insertion sort 








Implementation




__author__ = 'Dharmjit'
def selection_sort(list):
    for index in range(0, len(list)):
        iSmall = index
        for i in range(index,len(list)):
            if list[iSmall] > list[i]:
                iSmall = i
        list[index], list[iSmall] = list[iSmall], list[index]
    return list

if __name__ == '__main__':
    print(selection_sort([5,2,4,6,1,3,]))

Bubble Sort - using Python




Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.


Explanation

Let us take the array of numbers "7 6 5 4 3 2 1", and sort the array from lowest number
to greatest number using bubble sort. In each step, elements written in blue  are being compared.
 six passes will be required.

First Pass: swaps- 6
(7 6 5 4 3 2 1) --> (6 7 5 4 3 2 1)
(6 7 5 4 3 2 1) --> (6 5 7 4 3 2 1)
(6 5 7 4 3 2 1) --> (6 5 4 7 3 2 1)
(6 5 4 7 3 2 1) --> (6 5 4 3 7 2 1)
(6 5 4 3 7 2 1) --> (6 5 4 3 2 7 1)
(6 5 4 3 2 7 1) --> (6 5 4 3 2 1 7)

Second Pass: swaps -5
(6 5 4 3 2 1 7) --> (5 6 4 3 2 1 7)
(5 6 4 3 2 1 7) --> (5 4 6 3 2 1 7)
(5 4 6 3 2 1 7) --> (5 4 3 6 2 1 7)
(5 4 3 6 2 1 7) --> (5 4 3 2 6 1 7)
(5 4 3 2 6 1 7) --> (5 4 3 2 1 6 7)
(5 4 3 2 1 6 7) --> (5 4 3 2 1 6 7)

Third Pass: swaps - 4
(5 4 3 2 1 6 7) --> (4 5 3 2 1 6 7)
(4 5 3 2 1 6 7) --> (4 3 5 2 1 6 7)
(4 3 5 2 1 6 7) --> (4 3 2 5 1 6 7)
(4 3 2 5 1 6 7) --> (4 3 2 1 5 6 7)
(4 3 2 1 5 6 7) --> (4 3 2 1 5 6 7)
(4 3 2 1 5 6 7) --> (4 3 2 1 5 6 7)

Forth Pass: swaps - 3
(4 3 2 1 5 6 7) --> (3 4 2 1 5 6 7)
(3 4 2 1 5 6 7) --> (3 2 4 1 5 6 7)
(3 2 4 1 5 6 7) --> (3 2 1 4 5 6 7)
 (3 2 1 4 5 6 7) --> (3 2 1 4 5 6 7)
(3 2 1 4 5 6 7) --> (3 2 1 4 5 6 7)
(3 2 1 4 5 6 7) --> (3 2 1 4 5 6 7)

fifth pass: swaps - 2
(3 2 1 4 5 6 7) --> (2 3 1 4 5 6 7)
(2 3 1 4 5 6 7) --> (2 1 3 4 5 6 7)
(2 1 3 4 5 6 7) --> (2 1 3 4 5 6 7)
(2 1 3 4 5 6 7) --> (2 1 3 4 5 6 7)
(2 1 3 4 5 6 7) --> (2 1 3 4 5 6 7)
(2 1 3 4 5 6 7) --> (2 1 3 4 5 6 7)

sixth pass : swaps - 1
(2 1 3 4 5 6 7)--> (1 2 3 4 5 6 7)
(1 2 3 4 5 6 7) --> (1 2 3 4 5 6 7)
(1 2 3 4 5 6 7) --> (1 2 3 4 5 6 7)
(1 2 3 4 5 6 7) --> (1 2 3 4 5 6 7)
(1 2 3 4 5 6 7) --> (1 2 3 4 5 6 7)
(1 2 3 4 5 6 7) --> (1 2 3 4 5 6 7)
------------------------
__author__ = 'kamal'def bubblesort(alist):
    for numofpass in xrange(0, len(alist)-1):
        for i in xrange(0, len(alist)-1):
            if alist[i] > alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp

alist = [7, 6, 5, 4, 3, 2, 1]
bubblesort(alist)
print("----O-u-t-p-u-t-----")
print(alist)

Output--

----O-u-t-p-u-t-----
[1, 2, 3, 4, 5, 6, 7]

Wednesday, July 8, 2015

Insertion Sort - using Python

Talk about Algorithms and sorting comes to mind at first as it is the king of algorithms. Not only because there are many sorting algorithms but sorting is the fundamental operation in computing. Sorting means arranging items in some specific order and we see these all the times when working on our files or folder and working in database when we need records in some certain fashion. Sorting also find its use in searching and other algorithms.

There are many sorting algorithms and we will describe each algorithm and its implementation one post at a time.


Insertion sort

Insertion Sort is one of the simplest sorting algorithm. It is same as we sort  cards in our hand. We look at cards from left to right pick the unsorted card and insert it at correct position.

Explanation


For explaining the insertion sort algorithm we have taken the below unsorted list having 5 elements.

5
1
3
2
4


On first Iteration Second element will be compared with the first element it is smaller than first element they are swapped resulting in below list

1
5
3
2
4

  
On second iteration 3rd element will be checked against 1st and 2nd element and below list is formed.

1
3
5
2
4


And so on till the last element...

1
2
3
5
4

  
Final sorted list

1
2
3
4
5



Implementation


__author__ = 'Dharmjit'
def InsertionSort(list):
    for index in range(1,len(list)):
        curr = list[index]
        position = index

        while position > 0 and list[position-1] > curr:
            list[position] = list[position-1]
            position = position - 1

        list[position] = curr
    return list

l = [2,1,5,3,9,6,7]
print(InsertionSort(l))
[1,2,3,5,6,7,9]
Time complexity

Best Case Scenario:- If the list is already sorted the insertion algorithm runs in O(n) time which is linear

Worst Case Scenario:- When the List is sorted in reverse order, it will take o(n^2) time which is quadratic.



Tuesday, July 7, 2015

Python | For..Loop examples

In Python (v2.7), we have 2 type of loops - For and While

In this post, we printed few know series. These are not useful as is, in  your application but these are surely going to help you in building logical concepts using loops.


1. Right triangle using multiples of 5

for x in range(5,50,5):
    for y in xrange(5,x,5):
        print y,
    print ""















2. Right triangle from group of numbers

for x in range(3,15,3):
    for y in xrange(3,x):
        print y,
    print ""











3. Left triangle

for x in xrange(1,5):
    for y in xrange(1,5):
        if y < 4 - x + 1:
            print " ",
        else:
            print y,
    print ""





 4. Pyramid structure

for x in xrange(1,5):
    for y in xrange(1,8):
        if (y >= 5 - x and y <= 5 + x - 2):
            print (x+y)-4,
        else:
            print " ",
    print ""

Monday, July 6, 2015

How to Learn Python??


Python is open source, high level, object oriented and interpreted programming language. It also supports functional programming. Python philosophy is that readability counts and simple is better than complex. It is defined as Zen of Python in PEP 20.

Python installation

Python is available in different versions, among them python 2.7 and python 3.3 are widely used. Python is available for download at https://www.python.org/downloads and is available for all the platforms (windows, linux, machintosh). Simply download and install python. Start writing code either using the default command line editor which comes in the python installation or you can install editor of your choice.

Start Learning

You can go through the python documentation or tutorials available online. Also if you like interactive learning you can enroll for online Python courses available on most of MOOC sites like edx, coursera, udacity. After learning basic python and its use you can move to area of you interest like web development, data science/machine learning or try your hands on some of the coding competition.
  
 And Python is awesome..
Just to show you how awesome python is below is shared two hello world function in python and java and C.

Java
package javaPractice;
public class HelloWorld {
 
 public static void main(String[] args) {
  System.out.println("Hello World");
 }

}


Python
def HelloWorld():
    print "Hello World"
HelloWorld()


C
#include <stdio.h>
main(){
    printf ("Hello World");
}