Posts

Showing posts from November, 2021

Bubble sort in Python

Image
 It is one of the simplest sorting techniques where it traverses the whole list by comparing adjacent elements and swapping to move the biggest element to the end one at a time. eg. list. [4,2,9,1,7,6] after step 1 [2,4,1,7,6,9] after step 2 [2,1,4,6,7,9] after step 3 [1,2,4,6,7,9] after step 4 [1,2,4,6,7,9] after step 5 [1,2,4,6,7,9] CODE: l1=list() 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) for i in range (1,n): #in the outer loop it will traverse through each index from 1 till the last     for j in range(0,n-i):         if l1[j]>l1[j+1]:             l1[j+1],l1[j]=l1[j],l1[j+1] # if current element is bigger than the following element # then their positions will be swapped             print(f"changing place of {l1[j+1]} and {l1[j]}: ")             print(l1)     print(f"{i} biggest elements have reached the right

Insertion Sort in python

Image
 In Insertion Sort , we sort the element in a list by taking 1 element at at a time and placing it in a position of sorted order. For eg , let a list be [45,23,56,8,34] In step 1 the first two elements will be compared and arranged accordingly . Then in step 2 the third element will be compared with the first two elements and inserted to create an order (ascending or descending) among the three elements and this process will be continued until all the elements have been arranged. CODE: l1=list() 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) for i in range (1,n): #in the outer loop it will traverse through each index from 1 till the last     for j in range(0,i): # in 2nd loop each element will be compared with every element before it         if l1[i]<l1[j]:             l1[i],l1[j]=l1[j],l1[i] # if current element is smaller than any

Binary search in python

Image
 l1=list() n=int(input("Enter the no. of elements: ")) for e in range(n):     ele=int(input("Enter value for element: "))     l1.append(ele) s=int(input("Enter number to be found: ")) l1.sort() #defining lowest and highest index l=0 h=n-1 while l<=h:     m=(l+h)//2     if l1[m]==s:         print(f"Found at index :{m} ")         break     elif l1[m]>s:         h=m-1     else:         l=m+1 else:     print("Not Found") PYTHON FILE LINK

Notes and some extra tips,tricks ,points ,suggestion etc

 VERSION == PY --VERSION "," inbetween variables gets printed as single space print(sep="abj") // single space will be replaced by abj print(end="axn") // after printing axn will be added in the end without any space inbetween escape sequence /t (tab space) /n (new line) module installation == py -m pip install <<module name>> comments - #  , """   """ By default the input is taken as string reserved words == help("keywords") alt+p previous command In shell if we directly type something within " " then it as whole will be displayed .(known as display) translator -- interpreter(line by line)=shell/interactive mode , compiler(whole program)=Script mode GUI Programming uses tkinter library "{index}".format(variable) will work same as variable in between text without multiple commas and inverted commas.    import random  x=5,y=5 then id(x)==id(y) Data type : Conplex: x=complex(2+5j) x=2+5j

Important function in python and Miscellaneous

1==1.0 is True but 0.1+0.2==0.3 is False while(true): continue if ,break ,try,except exception as e \n print(e/customized error) except executes after a error occurs in try # try  may/may not be printed completely exception can be specified : except namerror:,except typerror:, valuerror:,zerodivisionerror raise error-type("error statement") else: gets executed if try was succcessful and no break statement finally: gets executed irrespective of error __name__ == __main__ by default or name of module used import filename  , filename.funcname , from filename import variablename(or)* global (used inside function) works on whole variable and can change its value global- used at top of prog , defined var can be used anywhere local -used inside a func to use that var in the func only enumerate(iterable) # add counter to an iterable and returns it.Syntax == for index,item in enumerate(iterable) list/set/dict comprehension ==  a=[1,2,5,1128938,3198,993,8589] # b=[] """

Modules

 import module_name as alias For calling : module_name.func_name(arguments) Or from module_name import func1,func3 (or*)  For calling : func1(arguments)  func2(arguments) (Name Error)  dir(module_name) - describe all classes, functions and variables  Some default magic classes - builtins, cached, doc, file, loader, name, package, spec Note: Whenever a module is used in a program, its compiled file will be generated and stored in the hard disk permanently  Note: Custom made modules need to be in same folder as program or in default python path and this gets stored in variable PYTHONPATH While searching for modules when an import statement is used first preference is given to the folder the program is present in then python path and if not found even after that then an error.  LEGB Rule: Local, Enclosing, Global, Built-in  For passing arguments in a function in an indefinite order : Func1(arg2=value, arg1=val, arg3=val...)  A function can return multiple value which be later picked up by

File I/O - Text

Image
 Text Files - .txt,.c Binary files - .jpg,.dat f=open("file name",opening type) opening types: "r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists , [write only] r+,a+,w+  == read and write Difference between r+ and w+ (maybe) - r+ pointer at beginning and w+ pointer at end of file ‘rb’ will open for read in binary mode ‘rt’ will open for read in text mode Default is reading mode f.read()=variable f.close()= very imp to use after our work with a file is done f.read(n)==read first n characters f.readline()==read first line Writing it multiple lines allow it to read lines one by one  f.readline(n) - Read first n characters till the /n  If n is negative then it reads the

Classes and Objects

 camelCase PascalCase class PascalCase # always object = class()   to declare a object part of class and then perform functions memory is alloted only after the above step class ClassName:     class_attribute1=value1     attribute2=value2 object = ClassName() object_attribute= value # updates individual value or add new value object_attribute > class_attribule # more powerful(in times of calling them) self-> gets automatically replaced with object name # to use within a func in class self.variable object.fun()==class.fun(object) ** @staticmethod # written before def to make it as class.fun() # it is a decorator def __init__(self, {can contain more variable})==it gets automatically run even without calling when a object is created. eg. def __init__(self,a,b):                    self.a=a                    self.b=b object=class(5,80) the above is called a constructor and its arguments are written in object=class(arguments) __method__ are called dunder method types of function_names

JSON

 JSON - dict format pickle - binary format variable=json.loads(dict enclosed in " " ) variable-type=dict variable2=json.dumps(dict) variable type=str use double inverted commas only json.dump(dict,file loc) variable3=json.load(file loc) same for pickling just replace json with pickle pretty print works with dump and dumps print(json.dumps(json_dict,indent=5,sort_keys=True)) example codes: CODE1 import json import requests def main():     data={         'username':"james",         'active':True,         'subscribers':10,         'orders_total':10.39,         'orders_ids':['abc','83m','hhd9']     }     # print(data)     s=json.dumps(data)     print(s)     print(type(s))     data2=json.loads(s)     # assert data2==data     print(data2)     # with open('file.json','w') as f:     #     json.dump(data,f)     # with open(file.json','r') as f:     #     data3=json.load(f)     # asser

Exception Handling

 raise error_name("message") ERRORS: NameError-undefined variable,mistype in variable/function name or name not enclosed in quotes TypeError- related to data types problems [eg. str doesn't work on int] ValueError-when a function gets wrong data type as input ZeroDivisinError AttributeError-using wrong methods or returning none/no return statement KeyError-dict IndexError IOError-file not found EOFError - end of file error FileNotFoundError IndentationError SYNTAX: try: except error1:runs if try has error1 except error2:runs if try has error2 Multiple exceptions can be specified in a except block. Eg except error1, error2 : else:runs if no error1 finally:always run, even if try block has return or break in it Python debugger module == pdb command prompt-$python-mpdbmycode.py pdb COMMANDS: l(lsit)-shows current position n(next)-next line excluding function s(step)-next line including function r(return)-steps to end of current executing function c(continue)-executes code q(

Important functions in python

 input print del  abs absolute value all() result true is all valid value , false if value contains false or 0 bin() converts to binary bool() format() getattr(class,"object") returns value of object of a class # also class.object iter and next # iterators len()  finds length list() open("file location") map() divmod(N1,N2) result == (quotient,remainder) filter() sorted() pow() power eg pow(4,2) == 4**2 range() reversed() round() type() zip() vars() __init__ eval('15+10')==25 # convert string to int or float accordingly id(variable)==place where variable is stored return == makes output of a function default input eg. def function(variable='something') try: sub part of function except: runs if try shoes error ** yield - generates a output as an object in memory continue: return back to the next iteration skipping any statement after it ord("alphanumeric")==ascii code chr(ascii code)==alphanumeric

List and Tuple

LIST list=[1,2,"hello",4,5] l[position_index]=something -- update value of element slicing - also starts from 0 While performing slicing if we enter any out of bound values then it will not show an error.  FUNCTIONS: l.sort()= creates list in ascending order # eg. print(l.sort()) l.reverse()=reverse the order of elements in list l.append(something)== add new items at end of list(individual item 1 or multiple) l.insert(position_index,item to be added)== insert new item in between    [typeError if only 1 argument given] (if the positive index entered is bigger than list length then value gets added at last/end)  l.pop(position_index)==remove item [if nothing specified then last item]   [can give index error] pop function also returns the deleted element i.e. prints it in interactive mode(if used) l.remove(element in list)== remove first occurrence item [value error if not in list][type error if not specified] del l1[index/range]   [can give index error] l.extend(list2)==add ite

Dictionary and Sets in Python

 Dictionary d={     "key1":"value1"     "key2":"value2" } d[key1] # output = value1  # will show error if key is incorrect Keys need to be of immutable data types eg, string,tuple or int  every key is unique,d is unordered [so no indexing]**,mutable Dictionary methods: d.keys()==print value of all keys as list (class=dict_keys) (list) output as dict_keys([list of keys]) d.values()==print all the values(list) output as dict_values([list of values]) d.items()== create a list of multiple tuples each having 2 elements :1 key and 1 value. output as dict_items([list of tuples]) d.update(d2)==add new item(s) of d2 in original dictionary at the end. or d[new_key]=new_value d.update("old_key","new_value")==replaces old value with new value d.get("key",error_message/value)== shows the related value or none # no error[default error message=None] print(d.get(...)) d.pop("key") d.clear() d.fromkeys(<a list of keys>

Escape Sequence

 A n escape sequence refers to a combination of characters beginning with a back slash (\) followed by letters or digits. Escape sequences represent non-printable and special characters in character and literal strings. As such, they allow users to communicate with a display device or printer by sending non-graphical control characters to specify actions like question marks and carriage returns. Credits for defination \\ backslash \' single quote \"double quote \a bell(plays beep sound) \b backspace \f formfeed(useless) \n linefeed(newline) \r carriage return(eg 1234567/rhello==hello67) \t horizontal tab \v vertical tab(useless) special charcters with their special meanings. occupies 1 charcter space

ASCII and Print Formatting

ASCII - american standard code for information interchange  ord("alphanumeric")==ascii code chr(ascii code)==alphanumeric A-Z -65-90 a-z -97-122 0-9 48-57 immutable -we can't change their values in place. in place imp. Print Formatting print(file=file_location) print(f/F"text {special value}") print(f'{variable_name = }') #output == variable_name = variable_value print(f'{variable_name!a}')==show ascii code instead of symbol if any print(f'{variable_name!r}')==print(repr(variable_name)) print(f'{variable_name!s}')== simple str print str vs repr is that repr also print the inverted commas (') repr()-it is generallly used for debugging for custom class objects it returns the name and address of object inside <>. Formatting: f'{date_variable:%Y %m %d}' f'{deci_val:.nf}'#n= number of decimal values to be printed class : class MyClass:     def __format__(self,format_spec) -> str:         print(f'Text i

Strings in Python

 str ="jhdvh" str="   howuulurh / hkhrf" the backslash above wrap text and print the result in a single line  Writing r before a string opening “ treats all the \ as backslash and not as escape sequence. immutable indexing 0:4 or -5:-1 print(str[startvalue(included):endvalue(not_included),skip_value]) print("a"+"b")==ab print("a"*b)==a a a a a ...b times Functions: len(str)==gives length of string str.endwiths("abc")==gives true or false based on if str ends with abc or not str.count("<<any letter or keyword>>")== returns how many times something appears in str NOTE : print("xyyyzxyy". Count("yy")) output will be  2  str.capitalize(empty)==makes first character of the STR capital str.find("something")== returns position index if present(first occurrence) else -1 str.replace("thing to be replaced","thing replaced with.")-replaces all occurrence str.strip(&q

Reserved words in Python Programming language

Reserved words(/keywords) in Python Programming language: and except lambda with as finally nonlocal while assert false None yield break for not class from or continue global pass def if raise del import return elif in True else is try await async