Month: June 2017

Classes In Python

Quick overview of the syntax of class in python. Simple form: class NameOfClass: attributes . . . More wholesome form: class ClassExample: """Documentation part """ attribute = "Class Variable" # class varirable which is shared by all its instances def function(self): # self == object/instance return "Function called" def __init__(self, instance_var): # Constructor like. No return statement. Only initialization self.inst_var = instance_var # unique to each instance obj = ClassExample("Instance Variable") print( obj.attribute, "\n"+obj.inst_var, "\n"+obj.function(), "\n"+obj.__doc__ ) OUTPUT Class Variable Instance Variable Function called Documentation part Inheritance concept is also included in Python. class Base: some_list = [] # common ... Read more

String Manipulations In Python

String Concatenation using ‘+’ upper() lower() split() str() len() format() Substitution and Date Time str1 = "Some text" str2 = " Some other text" concatenate_str = "Concatenation: " + str1 + str2 print(concatenate_str) format_str = "firs the tab \t then the new line \nthis format takes effect only after using in \'print\' \ inline break which isn't \"line break\" ".lower() cap_str = "\ncapitalized".upper() print(format_str) print(cap_str) print("-----------------") some_text = "Splitting to get words, or with comma" print(some_text.split()) print(some_text.split(",")) print("Length of some_text: " + str(len(some_text))) print("\n-----------------") print("SUBSTITUTION\n") subst_text = "With {variable} substitution.".format(variable="variable") print(subst_text) subst_text = "With {0} {1}.".format("positional", "substitution") print(subst_text) subst_text = ... Read more

Functions In Python

Function is basically used for making code re-usable. The keyword in python to define function is ‘def’. def function_name( parameters ): #body of function print "Hello Wolrd" return (some-expression-or-variable)  All parameters in Python are pass by value i.e. modifying parameter value inside function will reflect the changes in variable outside the function. Let’s learn more about python functions through code. def variable_change_test( some_var, some_list ): some_var = 21; #NOTE: We are creating a new local variable using assignment operator some_list.append(4) print("some_var inside function: ", some_var) print("some_list inside function: ", some_list) return some_var = 11 some_list = [1,2,3] variable_change_test(some_var, some_list) print("-------------------------") ... Read more

MergeSort In Java

Uses Divide and Conquer strategy like QuickSort. It divides the array of numbers into sub-arrays (from middle) until there is only one element in each sub-array. These sub-arrays are then merged into sorted sub-arrays until we obtain a sorted merged array. Stable Best Case Time Complexity: O(n log n) Worst Case Time Complexity: O(n log n) Space Complexity: O(n) public class MergeSortInJava { void sort(int arr[], int l, int r) { if (l < r) { // Find mid int m = (l+r)/2; // Sort first and second halves with recursion sort(arr, l, m); sort(arr , m+1, r); // Merging ... Read more

QuickSort In Java

Divide and Conquer Strategy Space required is less as compared to other sorting algorithms Not Stable Best Case Time Complexity: O(n log n) Worst Case Time Complexity: O(n^2) Space Complexity: O(n log n) class QuickSortInJava { /* The main function that implements QuickSortInJava() arr[] --> Array to be sorted, low --> Starting index (min. is 0), high --> Ending index (max. is n-1)*/ void sort(int arr[], int low, int high) { if (low < high) { /* correctPivotPos is index of pivot at its correct position i.e. arr[correctPivotPos] */ int correctPivotPos = partition(arr, low, high); // Recursively sort numbers sort(arr, ... Read more

Selection Sort In Java

0,1,…, n-1 index numbers are exchanged with smallest number from index numbers: 1,2,…,n Best Case Time Complexity: O(n^2) Worst Case Time Complexity: O(n^2) Space Complexity: O(1) Stable public class SelectionSortInJava { public static void SelectionSort(int[] arr){ for (int i = 0; i < arr.length - 1; i++) // excludes last element { int index = i; for (int j = i + 1; j < arr.length; j++){ // excludes first element if (arr[j] < arr[index]){ // find index of element smaller than key && smallest in the group of numbers to the right of key index = j; // searching ... Read more

Insertion Sort In Java

Sorts by shifting elements. All, but first element, are made as key once. Efficient for sorting few numbers. Insertion Sort is better than Selection Sort and Bubble Sort. Stable i.e. order of same numbers is maintained. /* 1. All elements other than 1st are considered as key 2. The key is compared with all previous elements until key is put at right place */ //Best Case: O(n) //Worst Case: O(n^2) //Space Complexity : O(1) public class InsertionSortInJava { public static void InsertionSort(int array[]) { int n = array.length; for (int j = 1; j < n; j++) { int key ... Read more

LinkedList in Java

Header: java.util.LinkedList<E> (where E denotes the type of elements in the collection) Some of the useful methods: addFirst(E e) addLast(E e) clear() clone() – returns a shallow copy of the Linked List contains(Object o) – returns true if list contains the object get(int position) getFirst() getLast() indexOf(Object o) remove() – retrieves and removes the head of the list remove(Object o) – removes first occurrence of the object o. removeFirst() removeLast() set(int position, E e) size() toArray() EXAMPLE import java.util.*; import java.io.*; class Book { int id; String name; public Book(int id, String name) { this.id = id; this.name = name; } ... Read more

Tuples in Python

Tuples are very much like lists but the difference is that tuples cannot be changed. Tuples are denoted by: () whereas lists are denoted by: [] To access element in tuple we make use of square brackets. E.g. tup[0] Tuples have similar functions as list as they are: cmp(tup1, tup2) len(tup) max(tup) min(tup) tuple(sequence) Let’s see tuples in action: >>> tup = () >>> tup = ("xyz", "xyz") >>> tup ('xyz', 'xyz') >>> tup = ( ... ("one", "one"), ... ("two", "two"), ... ) >>> tup (('one', 'one'), ('two', 'two')) >>> tup[0] ('one', 'one') >>> tup[0][0] 'one' >>> tup += ... Read more

Dictionary in Python

Dictionary in Python is represented with key value pairs. Keys must be unique whereas values are not. Let’s understand some basics by example: >>> a_dict = {} >>> a_dict = { "abc" : "String 1" } >>> a_dict {'abc': 'String 1'} >>> a_dict["abc"] = "String Change" >>> a_dict {'abc': 'String Change'} >>> a_dict["abc"] 'String Change' >>> a_dict[0] = "New dictionary item where key is integer" >>> a_dict {'abc': 'String Change', 0: 'New dictionary item where key is integer'} >>> a_list = [1,2,3] >>> a_dict['some_list'] = a_list >>> a_dict {'abc': 'String Change', 0: 'New dictionary item where key is integer', 'some_list': ... Read more