Sunday, August 30, 2020

Merging two sorted arrays - Big O (n+m) time complexity

 Problem : 

Merge the two sorted arrays.

Edge case : 

Array can empty

Arrays can be in different size



let getMaxLength = (input1,input2) => {
if(input1.length < input2.length) {
return input2.length;
}else {
return input1.length;
}
}
function mergeSortedArrays(input1,input2){
result = [];
let x = 0;
let y = 0;
if(!input1 || input1.length == 0){
return input2;
}
if(!input2 || input2.length == 0){
return input1;
}

let maxLength = getMaxLength(input1,input2);
while(x < input1.length && y < input2.length){
//find first smallest element between two arrays
if(input1[x] < input2[y]){
// x is smaller
result.push(input1[x++]);
}else{
// y is smaller
result.push(input2[y++]);
}
}
// add remaining array elements into result array
while(x < input1.length){
result.push(input1[x++]);
}

while(y < input2.length){
result.push(input2[y++]);
}

return result;
}

function print(result) {
for(index in result){
console.log(result[index]);
}
}
a = [1,5,7];
b = [2,6,31,44];

//print(mergeSortedArrays(a,b));
//print(mergeSortedArrays([],b));
print(mergeSortedArrays(a,[]));
//print(mergeSortedArrays([],[]));




Saturday, August 15, 2020

Basic Python jupyter notebook

 

Variable

a = 10
c = 10.2
b = False
d = 'A'
e = "Apple"

print(a)
print(b)
print(c)
print(d)
print(e)
10
False
10.2
A
Apple

Operator & Precedence

result = 10 + 20
print(result)

result = 1 + 1 * 10 + 30
print(result)

result = 1 + 2 * 10 + 30
print(result)

result = (1 + 1) * (10 + 30)
print(result)
30
41
51
80

Function

def delivery_check(pincode):
    print("delivery to ",pincode)

delivery_check("600100")
delivery to  600100

Main function

def start():
    print("Hello from main function")
    
if __name__ == "__main__":
    start()
Hello from main function

Class, Object and Method

class Order:
    def __init__(self,id,pincode):
        self.id = id
        self.pincode = pincode
    def display(self):
        text = "Order : {id}, to : {pincode}"
        print(text.format(id = self.id,pincode=self.pincode))

order = Order(101,600100)
order.display()
Order : 101, to : 600100

Inheritence

class NonVegOrder(Order):
    def __init__(self,id,pincode):
        super().__init__(id,pincode)
        
order = NonVegOrder(101,600100)
order.display()
Order : 101, to : 600100

String & Array

name = "Test"
char_name = ['p','y','t','h','o','n']
name = ""
new_name = name.join(char_name)
print(new_name)
print(name)
python
Test

List & Loop

char_name = ['p','y','t','h','o','n']
name = ""
for c in char_name:
    name = name + c
    
print(name)    
['p', 'y', 't', 'h', 'o', 'n', '.']

List

names = list(("Ranjith","Raj"))
print("Names length : ",len(names))
names.append('D')
print(names)
Names length :  2
['Ranjith', 'Raj', 'D']

Array

import array as a

digits = a.array("i",[1,2,3])
for d in digits:
    print(d)
1
2
3

if & else

check = False
if check :
    print("Its true")
else:
    print("Its false")
Its false

Dictionary

map = {
    "java": 100,
    "rust" : 200,
    "python": 300
}
print(map["java"])
100

Read input

number = int(input("Enter input"))
if number < 10:
    print("Number less than 10")
else:
    print("Number greater than or equal to 10")
Enter input23
Number greater than or equal to 10

Import

import time


print(time.ctime(time.time()))
    
Sat Aug 15 20:24:50 2020

Threading

import threading

def printme(name):
    print(name)

thread = threading.Thread(printme("first"))
thread.start()
first

Multi threading

import threading
import time


class MyThread(threading.Thread):
    def __init__(self, name,count,sleep_time):
        threading.Thread.__init__(self)
        self.name = name
        self.count = count
        self.sleep_time = sleep_time
        
    def run(self):
        for i in range(0, self.count):
            print(self.name,i)
            time.sleep(self.sleep_time)


thread1 = MyThread("Fast",5,0.5)
thread2 = MyThread("Slow",5,1)
thread1.start()
thread2.start()
print("Main thread done")
Fast 0
Slow 0
Main thread done
Fast 1
Slow 1
Fast 2
Fast 3
Slow 2
Fast 4
Slow 3
Slow 4

Thread join

import threading
import time


class MyThread(threading.Thread):
    def __init__(self, name,count,sleep_time):
        threading.Thread.__init__(self)
        self.name = name
        self.count = count
        self.sleep_time = sleep_time
        
    def run(self):
        for i in range(0, self.count):
            print(self.name,i)
            time.sleep(self.sleep_time)


thread1 = MyThread("Fast",5,0.5)
thread2 = MyThread("Slow",5,1)
thread1.start()
thread2.start()
thread1.join() # Current Main thread joined to thread1 to complete
thread2.join() # Current Main thread joined to thread2 to complete 
print("Main thread done")
FastSlow 0
 0
Fast 1
SlowFast 1
 2
Fast 3
Slow 2
Fast 4
Main thread done
Slow 3
Slow 4

Logging

import logging

logger = logging.getLogger('MyApplication')
logger.info('This is to showcase info level logging in python')
level = "Warning"
logger.info('This is to showcase %s level logging in python',level)
21:08:57: This is to showcase info level logging in python
21:08:57: This is to showcase Warning level logging in python

JSON

import json

order = '{"id" : 10,"user" : "ranjith"}'

order_json = json.loads(order) # Convert string to json
print(order_json['id'])
print(json.dumps(order_json)) # Convert json to string
10
{"id": 10, "user": "ranjith"}

Friday, August 14, 2020

Training session - Python - Class and Object

Order Domain

class Order:
    def __init__(self,count,deliveryAddress,phonenumber,landmark1,buyerName,specialNotes,status):
        self.count = count
        self.deliveryAddress = deliveryAddress
        self.phonenumber = phonenumber
        self.landmark1 = landmark1
        self.buyerName = buyerName
        self.specialNotes = specialNotes
        self.status = status

def processOrder(order):
    if order.count > 15:
        print("Limit exceeded")
    else:
        print(order.count,"Burger","+ Toping")
        print("delivered to ",order.deliveryAddress)
        print("phonenumber:  ",order.phonenumber)

burgerOrder = Order(10121123123123122176,"cdm",230,"mainroad","ran","","ordered")
processOrder(burgerOrder)

Book Domain

class Book:
    def __init__(self,index,page):
        self.index = index
        self.page = page
    def read(self):
        txt = "Index : {index}, Page :  {number:.2f}"
        return txt.format(number = page.get_number(),index = index.get_content())
    
class Page:
    def __init__(self,number):
        self.number = number
    def get_number(self):
        return self.number
        
class Index:
    def __init__(self,content):
        self.content = content
    def get_content(self):
        return self.content
        
index = Index("Holly")
page = Page(10121123123123123123)
book = Book(index,page)
print(book.read())

Merging two sorted arrays - Big O (n+m) time complexity

 Problem :  Merge the two sorted arrays. Edge case :  Array can empty Arrays can be in different size let getMaxLength = ( input1 , input...