Showing posts with label Algorithm. Show all posts
Showing posts with label Algorithm. Show all posts

Thursday, April 1, 2021

Find Max Memory, CPU% of a Subprocess in Python

This program uses psutil to track a job



import atexit

import math

import psutil

import time



cmd = './fib.py' #the script which we will track memory and cpu. It is a simple fibonace series printing program here without any print statement. It can be anything 

child_process = psutil.Popen(cmd, shell=True)


def kill_job():

    if child_process.is_running():

        child_process.kill()

        #child_process.kill


def convert_size(size_bytes):

   if size_bytes == 0:

       return "0B"

   size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")

   i = int(math.floor(math.log(size_bytes, 1024)))

   p = math.pow(1024, i)

   s = round(size_bytes / p, 2)

   return "%s %s" % (s, size_name[i])


atexit.register(kill_job)


print('PID=', child_process.pid)


counter = 0

max_memory = 0

while 1:

    child_process.poll()

    if child_process.is_running():

        cpu_percentage = child_process.cpu_percent(interval=1)

        cpu_times = child_process.cpu_times()

        memory = child_process.memory_full_info().rss #RES stands for the resident size, which is an accurate representation of how much actual physical memory a process is consuming.

        print('cpu_percentage', cpu_percentage)

        print('cpu_times', cpu_times)

        max_memory = max(memory, max_memory)

        print('memory', memory)

    else:

        print('not running')

        break

    counter += 1

    if counter > 5:

        kill_job()

    time.sleep(1)


print(max_memory)

Friday, April 22, 2016

Level Order Traversal in a Binary Tree from Bottom to Top

    public void LevelOrderReverse()    {
        System.out.println(LevelOrderReverse(this));
    }
    private String LevelOrderReverse(BinarySearchTree T)    {
        StringBuffer sb = new StringBuffer();
        if(T!=null)    {
            Queue<BinarySearchTree> Q = new LinkedList<BinarySearchTree>();
            Stack<BinarySearchTree> S = new Stack<BinarySearchTree>();
            Q.add(T);
            while(Q.size() > 0)    {
                BinarySearchTree C = Q.remove();
                if (C.right != null)
                    Q.add(C.right);
                if (C.left != null)
                    Q.add(C.left);
                S.push(C);
            }
            while(S.size() > 0)
                sb.append(S.pop().data).append(", ");
        }
        return sb.toString();
    }

Wednesday, April 20, 2016

Amazon Question: +1 or -1 Array Searching

Given an array, next element is either +1 or -1 of previous element then find any number k ?

    public int getIndex(int element, int[] input) { //element = k
        int size = input.length;
        for(int i=0; i < size;) {

            if(input[i]==element)
                return i;
            i=i+getPositive(element - input[i]);
        }
        return -9999; // element not found
    }
    private int getPositive(int i)    {
        if (i>0) return i;
        return (i * -1);
    }


Example 1:
Input: 4 5 4 5 6 7 8 9 8 9 10 11
k = 8
Output = 6

Example 2:
Input: 11 10 9 8 7 6 5 4 5 6 7 8 9 10 11
k = 4
Output = 7

Bucket Sort

Amazon Question: Given an array with 3 distinct elements, sort the elements in O(n) complexity
Input: 1,3,1,2,3,1,2,2,3
Output: 1, 1, 1, 2, 2, 2, 3, 3, 3


import java.util.ArrayList;

public class BucketSort {
    ArrayList> bucket;
    private int count;
    public BucketSort(int unique_int_count) {
        this.count = unique_int_count;
        this.bucket = new ArrayList>();
        for(int i=0; i <
this.count; i++) {
            bucket.add(new ArrayList());
    }
    public ArrayList Sort(ArrayList input)    {
        for(int c:input)    {
            if(c==1)    {
                bucket.get(0).add(c);
            }    else if(c==2)    {
                bucket.get(1).add(c);
            }    else    {
                bucket.get(2).add(c);
            }
        }
        ArrayList sorted_output = new ArrayList<>();
        for(int i=0; i < count; i++) {

            sorted_output.addAll(bucket.get(i));
        return sorted_output;
    }
    @Override
    protected void finalize() throws Throwable {
        bucket=null;
        super.finalize();
    }
}
//----------------------Main Method------------------------

    public static void main(String[] args) {
        BucketSort b = new BucketSort(3);
        ArrayList input = new ArrayList();
        input.add(1);
        input.add(3);
        input.add(1);
        input.add(2);
        input.add(3);
        input.add(1);
        input.add(2);
        input.add(2);
        input.add(3);
        System.out.println(b.Sort(input));
    }

Sunday, March 6, 2016

Find if a Tree is a Binary Search Tree

public boolean isBinarySearchTree() {
return isBinarySearchTree(this, -99999, 99999);
}
public boolean isBinarySearchTree(BinarySearchTree T, int min, int max) {
if(T==null)return true;
if(T.data>min && T.data<max 
&& isBinarySearchTree(T.left, min, T.data) && isBinarySearchTree(T.right, T.data, max))
return true;
return false;
}

Monday, February 15, 2016

Find Maximum Sum of a SubArray

Example Input: -1,2,6,4,-4,-5,56,78,-2,9
Desired Output: 134 

    public int MaxSumOfSubArray(int... input)    {
        int size = input.length;
        int max = 0;
        boolean isIn = false;
        int current_sum = 0;
        int previous = -1;
        for(int i=0; i<size; i++)    {
            if(!isIn) current_sum = 0;
            if(input[i]>=0)    {
                isIn = true;
                current_sum = current_sum+input[i];
            }    else if(previous>=0 && max<current_sum)    {
                max = current_sum;
                isIn = false;
            }
            previous = input[i];
        }
        return max;
    }

Sunday, February 14, 2016

Rotate an Array

    public int[] rotate(int count, int... input)    {
        for(int i=0; i&lt;count; i++)    {
            input = rotate(input);
        }
        return input;
    }
    private int[] rotate(int... input)    {
        int s =  input.length-1;
        int[] output = new int[input.length];
        for(int j=0; j < s; j++)    {
            output[j+1]=input[j];
        }
        output[0]=input[s];
        return output;
    }

Sunday, December 27, 2015

Print all sub-set of a given set

    public HashSet<HashSet<Integer>> getAllSubset(HashSet<Integer> set)    {
        int[] superSet = getHashToIntArray(set);
        double max = Math.pow(2, superSet.length);
        HashSet<HashSet<Integer>> result = new HashSet<HashSet<Integer>>();
        for(int i=1; i<=max; i++)    {
            int n=i;
            HashSet<Integer> subset = new HashSet<Integer>();
            for(int j=0; j<superSet.length; j++)    {
                if(n%2==1)
                    subset.add(superSet[j]);
                n=n/2;
            }
            result.add(subset);
        }
        return result;
    }
   
    private int[] getHashToIntArray(HashSet<Integer> set)    {
        int[] result = new int[set.size()];
        int i=0;
        for(Integer n: set)    {
            result[i]=n;
            i++;
        }
        return result;
    }

Friday, December 25, 2015

Convert Numeric to Binary

With Recursion: 
    public StringBuffer convertToBinary(int n)    {
        if (n<2) return new StringBuffer().append(n);
        return new StringBuffer().insert(0, n%2).insert(0, convertToBinary(n/2));
    }


Without Recursion:
    public String convertToBinary(int n)    {
        StringBuffer result = new StringBuffer();
        while(n>0)    {
            result.insert(0, n%2);
            n=n/2;
        }
        return result.toString();
    }

Tuesday, December 15, 2015

Get All SubArray of a given Array

    public ArrayList<ArrayList<Integer>> getAllSubArray(int[] a)    {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        for(int subarray_size=1; subarray_size<a.length; subarray_size++)    {
            ArrayList<Integer> newList = new ArrayList<Integer>();
            for(int i=0; i<a.length; i++)    {
                if((subarray_size+i)>a.length-1)
                    break;
                newList.add(a[i+subarray_size]);
                result.add(new ArrayList<>(newList));
            }
        }
        return result;
    }

Find if a Tree is a Mirror copy of another Tree

    public boolean isMirrorTrees(BinaryTree T1, BinaryTree T2)    {
        if(T1==null && T2==null)
            return true;
        if(T1.data!=T2.data)
            return false;
        if((T1==null && T2!=null) || (T2==null && T1!=null))
            return false;
        if(isMirrorTrees(T1.left, T2.right)
                && isMirrorTrees(T2.left, T1.right))
            return true;
        return false;
    }

Create a Mirror Copy of a Binary Tree

    public BinaryTree MirorCopyOfTree(BinaryTree T)    {
        BinaryTree newTree = new BinaryTree(T.data);
        if(T.left!=null)
            newTree.right=MirorCopyOfTree(T.left);
        if(T.right!=null)
            newTree.left=MirorCopyOfTree(T.right);
        return newTree;
    }

Wednesday, December 9, 2015

Insert Sorted Array into a Binary Search Tree with minimum height

public class BinarySearchTree {
    BinarySearchTree left, right;
    int data;
    public BinarySearchTree(int... SortedArrayOfdata) {
        int mid=SortedArrayOfdata.length/2;
        this.left=null;
        this.right=null;
        this.data=SortedArrayOfdata[mid];
        insertSortedArray(SortedArrayOfdata, 0, mid-1);
        insertSortedArray(SortedArrayOfdata, mid+1, SortedArrayOfdata.length-1);
    }
    private void insertSortedArray(int[] a, int startIndex, int endIndex)    {
        if(startIndex<=endIndex)    {
            int mid=(startIndex+endIndex)/2;
            insert(a[mid]); //Insert method is available here: link
            insertSortedArray(a, startIndex, mid-1);
            insertSortedArray(a, mid+1, endIndex);
        }
    }

}

Example Input:
BinarySearchTree BST = new BinarySearchTree(0,1,2,3,4,5,6,7,8,9,10,11,12,13);

Tuesday, December 8, 2015

Quick Sort

import java.util.Random;

public class QuickSort {
    int[] a;
    public QuickSort(int[] a) {
        this.a = a;
    }
    public int[] QSort()    {
        QSort(this.a, 0, this.a.length-1);
        return a;
    }
    private void QSort(int[] a, int startIndex, int endIndex)    {
        if(startIndex<endIndex)    {
            int PartionIndex = RandomizedPartition(startIndex, endIndex);
            QSort(a, startIndex, PartionIndex-1);
            QSort(a, PartionIndex+1, endIndex);
        }
    }
    private int RandomizedPartition(int startIndex, int endIndex)    {
        /* Worst Case of QuickSort is O(n^2)
        The possibility for WorstCase in QuickSort is very low
       
RandomizedPartition will help reducing the probability of the occurrence of worst case*/
        int PivotIndex=new Random().nextInt(endIndex-startIndex)+startIndex;
        swap(PivotIndex, endIndex);
        return Partition(startIndex, endIndex);
    }
    private int Partition(int startIndex, int endIndex)    {
        int Pivot=a[endIndex];
        int PivotIndex=startIndex;
        for(int i=startIndex; i<endIndex; i++)    {
            if(a[i]<=Pivot)    {
                swap(i, PivotIndex);
                PivotIndex++;
            }
        }
        swap(PivotIndex, endIndex);
        return PivotIndex;
    }
    private void swap(int IndexA, int IndexB)    {
        int temp=a[IndexA];
        a[IndexA]=a[IndexB];
        a[IndexB]=temp;
    }
}

Selection Sort

    public int[] SelectionSort(int[] a)    {
        for(int i=0; i<a.length; i++)    {
            int min=i;
            for(int j=i+1; j<a.length; j++)    {
                if(a[j]<=a[min])
                    min=j;
            }
            int temp=a[i];
            a[i]=a[min];
            a[min]=temp;
        }
        return a;
    }

Sunday, December 6, 2015

Insertion Sort

    public int[] InsertionSort(int[] input)    {
        for(int i=1; i<input.length; i++)    {
            int val=input[i];
            int hole=i;
            while(hole>0 && val<input[hole-1])    {
                input[hole]=input[hole-1];
                hole--;
            }
            input[hole]=val;
        }
        return input;
    }

Swap Two Integers without Temporary Variable

    public static void DoSwaping(int a, int b)    {
        a=a+b;
        b=a-b;
        a=a-b;
        System.out.println("a: "+a+"\nb: "+b);
    }

    public static void main(String[] args) {
        DoSwaping(5, 9); // Example Input
    }

Bubble Sort

    public int[] BubbleSort(int[] input)    {
        int size=input.length;
        for(int i=0; i<size; i++)    {
            boolean flag = true;
            int s=size-i-1;
            for(int j=0; j<s; j++)    {
                if(input[j]>=input[j+1])    {
                    flag=false;
                    input[j] = input[j]+input[j+1];
                    input[j+1] = input[j]-input[j+1];
                    input[j] = input[j]-input[j+1];
                }
            }
            if(flag) break;
        }
        return input;
    }

Merge Sort

    public int[] MergeSort(int[] a)    {
        int mid = a.length/2;
        if(mid<1)    return a;
        int[] left = new int[mid];
        int i=0;
        for(; i<left.length; i++)
            left[i]=a[i];
        left = MergeSort(left);
        int[] right = new int[(a.length%2==1)?(mid+1):mid];
        for(int j=0; j<right.length; j++)    {
            right[j]=a[i];
            i++;
        }
        right = MergeSort(right);
        return Merge(left, right);
    }
    private int[] Merge(int[] left, int[] right)    {
        int i, j, k;    i=j=k=0;
        int[] merged = new int[left.length+right.length];
        while(i<left.length && j<right.length)    {
            if(left[i]<=right[j])    {
                merged[k]=left[i];
                i++;
            }    else if(left[i]>right[j])    {
                merged[k]=right[j];
                j++;
            }
            k++;
        }
        while(i<left.length)    {
            merged[k]=left[i];
            i++; k++;
        }
        while(j<right.length)    {
            merged[k]=right[j];
            j++; k++;
        }
        return merged;
    }

Saturday, December 5, 2015

Chess Knight Move in Board

public class ChessBoard {
    int[][] Board;
    public ChessBoard() {
        Board = new int[8][8];
        for(int i=0; i<8; i++)
            for(int j=0; j<8; j++)
                Board[i][j]='E';//Empty
    }
    public void KnightMove(int x, int y)    {
        if(x>-1 && x<8 && y>-1 && y<8)
            Board[x][y]='K';//Knight
        else    {
            System.out.println("Error: Not valid Points");
            return;
        }
        int a=x+2;int b=y+1;
        if(a>-1 && a<8 && b>-1 && b<8)
            Board[a][b]='T';//Threten
        System.out.println(a+" "+b);
        a=x+2;b=y-1;
        if(a>-1 && a<8 && b>-1 && b<8)
            Board[a][b]='T';//Threten
        a=x-2;b=y+1;
        if(a>-1 && a<8 && b>-1 && b<8)
            Board[a][b]='T';//Threten
        a=x-2;b=y-1;
        if(a>-1 && a<8 && b>-1 && b<8)
            Board[a][b]='T';//Threten
        a=x+1;b=y+2;
        if(a>-1 && a<8 && b>-1 && b<8)
            Board[a][b]='T';//Threten
        a=x-1;b=y+2;
        if(a>-1 && a<8 && b>-1 && b<8)
            Board[a][b]='T';//Threten
        a=x+1;b=y-2;
        if(a>-1 && a<8 && b>-1 && b<8)
            Board[a][b]='T';//Threten
        a=x-1;b=y-2;
        if(a>-1 && a<8 && b>-1 && b<8)
            Board[a][b]='T';//Threten
        printBoard();
    }
    public void printBoard()    {
        for(int i=0; i<8; i++)    {
            StringBuffer sb = new StringBuffer();
            for(int j=0; j<8; j++)
                sb.append((char)Board[i][j]).append(", ");
            System.out.println(sb.toString());
        }
    }
}
UA-39217154-2