DSA

DSA

DATA STRUCTUTRE AND ALGORITHM

1.Printing

Printing and then moving cursor to next line

JS

console.log("hello sharpnerians");


Python

print("hello sharpnerians")


C++

cout<<"hello sharpnerians"<<endl;


Java

System.out.println("hello sharpnerians");



Printing and cursor remaining same line

JS

not possible


Python

print("hello sharpnerians", end="")


C++

cout<<"hello sharpnerians";


Java

System.out.print("hello sharpnerians");



2.Variables


its a placeholder to store values

x=3 //x is the variable


Datatype


its defined type of the data to be stored

primitive data type=it has value

Static defined datatype:

In some language, datatype should be mention

e.g. int x=5 //java


Dynamic defined datatype:

n some language, datatype should not be mention

e.g. x=5 //python




import java.util.*;
public class Main
{
    public static void add(int a,int b)
    {
        /* Write your code inside this block*/
       
   
        System.out.println(a+b);
       
       
        /* Do not change the code beyond this point*/
   
    }
    public static void main(String[]args)
    {
        Scanner sc=new Scanner(System.in);
        int a=sc.nextInt();
        int b=sc.nextInt();
        add(a,b);
    }
}



python:


def calculate(a,b, c): 5 """write the code inside this block to calculate a+b-c""" 6 print(a+b-c) 7 8 9 10 11 """Dont change anything below. If changed click on reset.""" 12 13def main(): 14 a = int(input()) 15 b = int(input()) 16 c = int(input()) 17 calculate(a,b,c) 18main()


x=8

y=3

print(x)


operator in python


print(x/y)

o/p=2.8


print(x//y)

o/p=2

--------------------------------------------------------------------------------------------

swap two numbers:


def swap(a,b): 5 """write the code inside this block to swap two numbers""" 6 x=b 7 b=a 8 a=x 9 10 11 """Dont change anything below. If changed click on reset.""" 12 print("a value is =",a) 13 print("b value is =",b) 14 15def main(): 16 a = int(input()) 17 b = int(input()) 18 swap(a,b) 19main()




IF ELIF ELSE



x=3

if x==3:

print("true")

else:

    print("false")


IF ELSE LADDER


def print_cost(distance): 5 """ 6 write the code below to print the cost 7 if the distance is given 8 """ 9 if distance<=100: 10 print("5") 11 elif distance>100 and distance<=500: 12 print("8") 13 elif distance>500 and distance<=1000: 14 print("10") 15 elif distance>1000: 16 print("12") 17





TERNERY OPERATOR


(if else statement in a single line)


java:

   x = a<10 ? 5 :10


if(a<10)

x=5;

else

x=10;


python:


syntax: opt1 if condition else opt2


e.g. 5 if a<10 else 10

           a = "xxx" if x<6 else "yyy"


e.g.        x=6

             print(10 if x>0 else 1)


e.g. x=5             a = "xxx" if x<6 else "yyy"             print(a)





SWITCH STATEMENT







--------------------------------------------------------------------------------------------------------------------------


LOOP


Execute particular statement continuously till the condition will reach


While loop:

    

        initialization

        condition

        incrementation


e.g.

        i=1

        while i<=5:

            print("Hello world")

            i=i+1


e.g. Print all even numbers from 1 to n


   def print_even(n): 5 6 i=2 7 while i<=n: 8 print(i) 9 i=i+2 10 11def main(): 12 n=int(input()) 13 print_even(n) 14 15main()





--------------------------------------------------------------------------------------------


FOR LOOP

Syntax:


for i in range(start, end inc/dec)


e.g.


for i in range(2, 11, 2):

print(n);


o/p

2 4 6 8 10


for i in range(10,1, -2):

print(n)


o/p 10 8 6 4 2


for i in range(25, -1,-5):

print(n)


o/p 25 20 15 10 5 0


e.g. for loop used with list

x=["sumi",34,1223]

for i in x:

print(x)


o/p sumi 34 1223


x="sumi"

for i in x:

print(i)


o/p s u m i


for i in x["sumi",23,455]

print(i)


o/p sumi 23 455


for i in range(10):

print(i)


o/p 012345678910


pattern


1st loop ------ pointing no. of lines

2nd loop-------pointing details of each line


for(10,

m=-1

y=mx+c

y=-1x+c

14=-1*2+c

c=16

formula =16-i

inner loop(10,16-i,1)






def print_message(message): 13 14 print(message) 15 16def main(): 17 while True: 18 try: 19 message = input() 20 21 except EOFError: 22 break 23main()


-------------------------------------------------------------------------------------------


Array
Dynamic Array


--> In python we use dynamic array(list) we dont mention the size if array
 --> In python memory get allocate in run time(compile time in java)
-->Collection of data on same type

import array as arr
..........
arr.array()




                                            O/P: 1











Function in array

Function for find size of array:




Function for find type of array:


                                            O/P:   i

Function for reverse the array:



Function for copy of array:


also:


Function for insert elements in array:
        Insert in between the array(particular index)


        Insert element at last:



        Insert a group of element:

Function for delete elements from array:
            Delete last element:
            pop()--->delete element using index value







            remove()-------->remove elements using that particular value


            Delete a group of elements:






Function for sort elements in array:




num=[11,22,33,44,55]
name=['sumi', 'suji', 'mono']

print(num[2])=====>33
print(num[2:])=====>33,44,55
print(num[-4])=====>11([-4],-3,-2,-1,0)

val=[num,name]
print(val)======>[11,22,33,44,55],['sumi', 'suji', 'mono']














Loop in array



also use:



Sub array

Contiguous(continues) part of array.
-->contiguous
-->part
-->forward

e.g. [1,4,2,3]
[1],[1,4],[1,4,2]-subarray
[2],[2,3]-subarray
[4,2,3]-subarray
[1,3]-not
[4,3]-not



Dynamic array

*NO fixed size



Sorting

1) Bubble sort


 
2) Insertion  sort

3) Selection sort
find min and max first

--------------------------------------------------------------------------------------------------------------


BIT MANIPULATION

*1 byte = 8 bits
*Decimal number to binary number conversion

*Binary to Decimal conversion



* Decimal to Octal conversion
 


*Octal to Binary Conversion







AND, OR, XOR



Right shift and Left shift

Right shift >>

10101>>0 
o/p 10101   // remove 0 element from right

10101>>2
o/p 101         // remove 2 element from right



Left shift <<

10101<<0 
o/p 10101  //append 0 zero to right

10101<<2
o/p 1010100 // append 2 zeros to right



use of Right shift:
    10101>>2 &1      //will find 3rd number
            101 & 001 = 1 //3rd number


Find maximum of array without using inbuilt fun max():

max=a[i]
if a[i]<a[j]:
    max=a[j]

Find most +ve and -ve number:




--------------------------------------------------------------------------------------------------------------

Time Complexity

Its a analysis of how much time your code take to run.



return-1unit
arithmetic operation-1 unit
total-2 unit





How to find time complexity?

= O(1)
Because the above statement will execute at only one time.

***********

loop execution=n+1
statement execution=n
we should only take the statement execution.
so O(n).

***************

loop execution=n+1
statement execution=n
we should only take the statement execution.
so O(n).

***************


loop execution=n+1
statement execution=n/2
we should only take the statement execution.
so O(n).

***************
statement execution=n*n                                                                                                            we should only take the statement execution.
so O(n^2).                                                                                                                                    ***************                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         

*************** 



************** 


************** 
************** 


************** 



****************



****************



****************


****************






--------------------------------------------------------------------------------


String

*Reference data type(storing address of data too like array)
-Sequence of character



Accessing character:



Find the length:




Iterating String:

Sub_string:


Character to ASCII value:


Type Conversion:

    *convert one data type to another

1)widening or automatic type conversion
    *Automatically convert lower part to upper part
    e.g. integer --> long
        

2)Narrowing and explicit type conversion
    * forceful conversion you should mention

 That you want to convert it to char


Concatenation: 

*String concatenation means add strings together. 
*Use the + character to add a variable to another variable.



Concatenation with type conversion:



Play with String:















String Method:

MethodDescription
capitalize()Converts the first character to upper case
casefold()Converts string into lower case
center()Returns a centered string
count()Returns the number of times a specified value occurs in a string
encode()Returns an encoded version of the string
endswith()Returns true if the string ends with the specified value
expandtabs()Sets the tab size of the string
find()Searches the string for a specified value and returns the position of where it was found
format()Formats specified values in a string
format_map()Formats specified values in a string
index()Searches the string for a specified value and returns the position of where it was found
isalnum()Returns True if all characters in the string are alphanumeric
isalpha()Returns True if all characters in the string are in the alphabet
isascii()Returns True if all characters in the string are ascii characters
isdecimal()Returns True if all characters in the string are decimals
isdigit()Returns True if all characters in the string are digits
isidentifier()Returns True if the string is an identifier

Sislower()
Returns True if all characters in the string are lower case
isnumeric()Returns True if all characters in the string are numeric
isprintable()Returns True if all characters in the string are printable
isspace()Returns True if all characters in the string are whitespaces
istitle()Returns True if the string follows the rules of a title
isupper()Returns True if all characters in the string are upper case
join()Joins the elements of an iterable to the end of the string
ljust()Returns a left justified version of the string
lower()Converts a string into lower case
lstrip()Returns a left trim version of the string
maketrans()Returns a translation table to be used in translations
partition()Returns a tuple where the string is parted into three parts
replace()Returns a string where a specified value is replaced with a specified value
rfind()Searches the string for a specified value and returns the last position of where it was found
rindex()Searches the string for a specified value and returns the last position of where it was found
rjust()Returns a right justified version of the string
rpartition()Returns a tuple where the string is parted into three parts
rsplit()Splits the string at the specified separator, and returns a list
rstrip()Returns a right trim version of the string
split()Splits the string at the specified separator, and returns a list
splitlines()Splits the string at line breaks and returns a list
startswith()Returns true if the string starts with the specified value
strip()Returns a trimmed version of the string
swapcase()Swaps cases, lower case becomes upper case and vice versa
title()Converts the first character of each word to upper case
translate()Returns a translated string
upper()Converts a string into upper case
zfill()Fills the string with a specified number of 0 values at the beginning



String format:


age = 36
txt = "My name is John, I am " + age
print(txt) 
o/p
Traceback (most recent call last):
  File "demo_string_format_error.py", line 2, in <module>
    txt = "My name is John, I am " + age
TypeError: must be str, not int



age = 36
txt = f"My name is John, I am {age}"
print(txt)

o/p
My name is John, I am 36


To extract a specific word from a string in Python, you can use the split() method to split the string into a list of words, and then access the desired word using its index.

Here's an example:

  1. text = "The quick brown fox jumps over the lazy dog." 
  2. word_index = 3 
  3. extracted_word = text.split()[word_index] 
  4. print(extracted_word) # Output: "fox" 

In this example, text.split() returns a list of words ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.'], and word_index = 3 selects the 4th word in the list, which is "fox".

--------------------------------------------------------------------------------

Select particular char from array string:


-------------------------------------------------------------------------------

OOPS

-Object Oriented Programming System
-Design pattern
-make readable 
-programming paradigm where the complete software operates as a bunch of objects talking to each other.

Class & Objects:

-class is template
-class is like a factory it produce products(objects).
-create class with keyword class and followed by its name.

eg. class car:

Function:

eg.
    def calculate_distance(self,speed,time):
        print(speed*time)

self--->helps compiler  to understand which particular object I want.



init(contructor):

*When the object is created then the constructor execute first.
*If I create 2 objects like obj1 & obj2 then the "init" function will execute 2 times.













Comments

Popular posts from this blog

React_JS

Java_Script