Posts

Showing posts from March, 2022

MERGE SORT

Image
Algorithm Divide the list in two half if length not = 1 or 2 sort left half  sort right half  merge the two  merging: compare the first element of each half then choose(and remove) the smaller , then check the next index of the sub list from which ele1 was chosen and repeat it until both sublists become empty IMAGE: CODE:  l1=[] n=int(input("Enter the number of elements in list: ")) for e in range(n):     ele=int(input("Enter value for element: "))     l1.append(ele) print("Original list :",l1) def merge(la,lb):     l1=list(la)     l2=list(lb)     l4=[]     i=(len(l1)+len(l2))     while len(l4)<i:         if len(l1)==0 or len(l2)==0:             l4=l4+l1+l2             break         if l1[0]>=l2[0]:             l4.append(l2.pop(0))         else:             l4.append(l1.pop(0))     return l4 def sort(l1):     l4=[]     if len(l1)==2:         if l1[0]<l1[1]:             return l1         else:             return l1[::-1]     else:         return l1

FILE I/O 2-BINARY, CSV

Image
  PATHS: import os  path=os.getcwd() The above function gives the current working directory to the var 'path' To write absolute path either use / or \\ between directories and file names Writing r before a string opening “ treats all the \ as backslash and not as escape sequence Standard File Streams These are file object which get automatically connected to input/output devices for performing action through them import sys Streams: sys.stdin- when reads from standard input sys.stdout- by default gets printed to screen and output can be put to a file sys.stderr- similar to stdout but also prints error msg , exceptions and debugging Methods: read()-for reading a byte at a time write(data)-writing data of a console(output device== monitor) Syntax : sys.stream.method - eg sys.stdout.write(“Hello world”) CSV- Comma Separated Values eg:  import csv 1.) Reading csv file: f=open("file name","r") data_table=csv.reader(f) here data_table is a sequence of lists in wh