Saturday, May 16, 2020

Python: Binary Search

Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.

The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).

class BinarySearch(object) :

    def binarySearch(self, A, K):

        # Returns index of x in arr if present, else -1 
    def binarySearch(arr, l, r, x):

       # Check base case             
       if r >= l:
                print("r,l:",r,", ",l)
                mid = round(l + (r - l) / 2)

                # If element is present at the middle itself 
                if arr[mid] == x:
                    return mid

                # If element is smaller than mid, then it can only 
                # be present in left subarray 
                elif arr[mid] ==  x:
                    print("search left side of the array: arr[mid] is ", arr[mid])
                    return binarySearch(arr, l, mid - 1, x)

                    # Else the element can only be present in right subarray                 
                else:
                    print("search right side of the array: arr[mid] is  ", arr[mid])
                    return binarySearch(arr, mid + 1, r, x)

            else:
                # Element is not present in the array 
                return -1

        result = binarySearch(A, 0, len(A)-1, K)
        return result

def main():
    x = BinarySearch()
    A = [10, 7, 8, 9, 1, 5]
    k = 1    #output = 8    #A =[7, 10, 4, 3, 20, 15]
    A.sort()
    print("array is: ",A)
    print("element ",k, " of array ", A, " is index ", x.binarySearch(A,k))

if __name__ == '__main__':
    main()

Friday, May 15, 2020

Python Convert 12 Hour to 24 Hour Time

For computation purposes, 24 hour time works better. Here is a function to convert the 12 Hour time String to 24 hour time string.
def time_convert_12_24(self,str_time):
    
    time_arr = str_time.split()  # split by space    n = time_arr[0].count(':')
    time_str : str ='' 
    if n == 1 :
       #5:30        
       time_str = time_arr[0]+':00'     
    elif n == 0 :
       #5 
       time_str = time_arr[0]+':00:00'     
    else :
       time_str = time_arr[0]
    #change 12:00 am to 00:00
    if time_arr[1].upper() == 'AM' and time_str[:1] == "12":
        "00" + time_str[2:-2]
    # add 12 hour to PM hours
    if time_arr[1].upper() == 'PM' :
        str_part = time_str.split(':')
        if int(str_part[0]) != 12 :
            return str(int(str_part[0]) + 12) +':'+str_part[1] + ':'+ str_part[2]
        else :
            return time_str
    else :
        return time_str

Thursday, May 14, 2020

Substitute Variables in PostgreSQL

It is useful to use variables in a SQL script. For example, when writing a create objects script, we can use a variable to store the schema name. This way, if we decide to change the schema name later, we just need to re-set the value for the variable.

\set dm_schema 'dm'
CREATE SCHEMA IF NOT EXISTS :dm_schema;

create table IF NOT EXISTS :dm_schema.user(
    user_id                          serial primary key,
    user_name                        VARCHAR(128),
    user_email                       VARCHAR(128)
  
);

create table IF NOT EXISTS :dm_schema.use_groupr(
   group_id                          serial primary key,
   group_name                        VARCHAR(128)
  
);