Posts

Grid Printing Code for Python

Image
 Github link : Click here Note: The code is open-source  but it highly advised to acknowledge this Web page or the github link whenever using this code in your project . The main aim of this is to allow for easy access to a 2d grid with x,y coordinates. It can be used to create a chess board, Maze or just anything you could think of with a grid.  The basic output look as follows: The variables defined are: The function in it are:  For customization : Change the variable x,y to alter the board size  Insert values in the _coords lists to get a particular pattern in a certain cell If you want to change the default cell filling then simply go to the end of print_board() function and under the heading default change the empty_cell function to any desired functions. I hope this code will help you sometime in future or it gave you an idea to make a better version of it (then don't forgot to share it to me via commenting it down).  Github link of the whole code:  Click here For any queries

FUNCTIONS

 Syntax for defining a function: def func_name(formal arguments/parameters):     #statements calling a function: func_name(actual argments) LEGB Rule for checking scope of variable: Local, Enclosing, Global, Built-in  For passing arguments in a function in any indefinite order : Func1(arg2=value, arg1=val, arg3=val...) - This method is called keyword arguments A function can return multiple value which be later picked up by a variable as tuple if a function doesn't return anything and it is called inside a print statement then the output will be 'None' Common built-in functions: Round(Number, no. of decimal to be rounded off)  Round(12.5)==12 Round(13.5)==14      if the second argument is in negative then it will start round off the tens, hundreds position and so on.  abs(number) - Returns absolute value as int ot floa

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

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