Posts

PYTHON - MYSQL CONNECTIVITY

To download MYSQL V5.7  CLICK HERE  To download connector via pip; python -m pip install mysql-connector Establishing connection  : To get username and password : select current_user(); The output is of form--username@host Import mysql.connector as m Mydb=m.Connect(host="localhost",user="root",passwd="your_mqsql_password") If print(Mydb) doesn't show any error then it means that the connection has been successfully made All the below commands need to written after the above commands which create a connection  Note: Alternate of localhost is 127.0.0.0 Alternate representation : <<1>>-host, <<2>>-user, <<3>> password Creating database: mycursor=Mydb.cursor() mycursor.execute("create database datbase_name")  If database already exits then it create an error To check if connected use : mydb.is_connected() To access a database  :   Method   1  : Same connection with a command an additional command at top mycurso...

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:...

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...

MYSQL NOTES

To download MYSQL V5.7  CLICK HERE Dbms-database management system r-relational by e.f.codd data is different from information mysql is not case sensitive for keywords Commands : show databases; show tables; use <database name>; create database <database name>; drop table <table name>; drop database <database name>; create database if not exists database_name create table <table name> no semicolon press enter (<column name> <data type> default "default value <quotes as per data type>", <column name> <data type> not null primary key, <column name> <data type> check(col_name >100) ); # column name no spaces #create from existing table: Create table table2_name // a select query in table 1.eg Select * from table 1 where marks>90; describe <table name> ;describe or desc # desc-show the structure of database insert into <table name>  #no semicolon press enter values(data1,data2,data3...); ...

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]}: ")   ...

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]...

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 retur...