Showing posts with label Java Programming. Show all posts
Showing posts with label Java Programming. Show all posts

Sunday, March 5, 2017

Python Cheat sheet

Recently I started to learn Python and found it very interesting and easy as well. I stated to learn python from level 0 and now I learned core Python in 10 days. Studied mostly from python.org, courcera.com and udemy.com.

python.org is official website of Python. Here I am sharing my digital Cheat Sheet on python which I have studied till now. Still I am continuing this. I will share the further notes soon.

Please provide comments and queries if you have.
---------------------------------------------- Python Notes ---------------------------------------------------------
Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum in the Netherlands as a successor of a language called ABC.
According to the principal author (Guido van Rossum), he chose the name "Python" because he is a big fan of the British comedy movie - 'Monty Python's Flying Circus'.

Salient features of Python:-
*  Python is a case sensitive programming language.
*  It supports functional and structured programming methods as well as OOP.
*  It can be used as a scripting language or can be compiled to byte-code for building large applications.
*  It provides very high-level dynamic data types and supports dynamic type checking.
*  It supports automatic garbage collection.
*  It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Type Conversion:-
str(x) − Converts object x to a string representation.
float(x) − Converts x to a floating-point number.
tuple(s) − Converts s to a tuple.
list(s) − Converts s to a list.
set(s) − Converts s to a set.
dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.
chr(x) − Converts an integer to a character.
hex(x) − Converts an integer to a hexadecimal string.
oct(x) − Converts an integer to an octal string.
round(x) - Round a float number to integer either to base or to floor according to float value.


isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
isdigit() − Returns true if string contains only digits and false otherwise.
islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
lower() − Converts all uppercase letters in string to lowercase.
upper() − Converts all lowercase letters in string to uppercase.
swapcase() − Inverts case for all letters in string.
capitalize() − Capitalizes first letter of string.
title() − Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.
istitle() − Returns true if string is properly "titlecased" and false otherwise.
isspace() − Returns true if string contains only whitespace characters and false otherwise.
lstrip() − Removes all leading whitespace in string.
rstrip() - Removes all the whitespace after the string.
strip([chars]) − Performs both lstrip() and rstrip() on string.
len(string) − Returns the length of the string.
random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.
str.rjust(width,'fillchar') -- print the string right justified.
str.rjust(width) -- we can use it simply like this.
str.center()  -- center justified
str.ljust() -- left justified

List:-
cmp(list1, list2) − Compares elements of both lists.
len(list) − Gives the total length of the list.
max(list) − Returns item from the list with max value. --all elements must be of same data type
min(list) − Returns item from the list with min value.  -- all elements must be of same data type
list.index(obj) − Returns the lowest index in list that obj appears.
list.insert(index, obj) − Inserts object obj into list at offset index.
list.append(obj) - Append obj in the list.
list.remove(obj) − Removes object obj from list.
list.reverse() − Reverses objects of list in place i.e. first index value goes to last and last to first.
example:- list=['abc', 454, 2.23, 'john', 70.2]  then output of list.reverse() is [70.2, 'john', 2.23, 454, 'abc']
list.sort([func]) − Sorts objects of list, use compare func if given.
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

**help(print) -- it displays help regarding parameter passed
**dir(<argument>) -- it displays help, what are function we can use with the argument

What is IDLE?
IDE - Integrated Development Environment.
IDLE - is IDE for Python.

We can use commands like -- 3+4,8-4,6/2,(2*4)+3/2 in python shell.
printing string in- >>> "Hello" or 'Hello' , x='dog'
print('Hello'),print('dog',5,4,'cat'),print(x)
Python remembers all the variables until is not restarted or deleted.
delete variable command: del <variable name/s>

Variable naming convention is same as C/C++. It contains letters,numbers and underscore.
Reserved identifiers in Python-


Variable tyes in Python
1. integer(int) (All integer type is long int)
2. float
3. Comples
4. string(str)
5. boolean(bool)
6. list
7. Tuple
8. Dictionaries
str = 'Hello World!'

print (str)               # Prints complete stringprint -- Hello World!
(str[0])                  # Prints first character of the stringprint -- H
(str[2:5])               # Prints characters starting from 3rd to 5th print -- llo
(str[2:])                 # Prints string starting from 3rd characterprint -- llo World!
(str * 2)                 # Prints string two timesprint -- Hello World!Hello World!
(str + "TEST")        # Prints concatenated string -- Hello World!TEST


The main differences between lists and tuples are −
* Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.
Example :- list1= ['abcd', 786, 2.23, 'john', 70.2]  ::: tuple1=('abcd', 786, 2.23, 'john', 70.2)

Dictionary defined in curly braces while value can be assigned and accessed by square braces [] .
dict1 = {'name': 'john','code':6734, 'dept': 'sales'}
dict1['one'] = 'Hello'
dict1[2] = 10

e.g. -
print (dict1['one'])              # Prints value for 'one' key
print (dict1[2])                   # Prints value for 2 key
print (dict1)                  # Prints complete dictionary
print (dict1.keys())        # Prints all the keys
print (dict1.values())     # Prints all the values

Operator types in Python:-
1. mathematical   2. Relational   3. Logical    4. Bitwise
5. Membership (in,not in)  e.g. 2 in [3,2,6]  Result:: True
6. Identity  (is,is not)   e.g. a is b -- Result will be True or False


Arithmatic operator othe then C++ --
//  -- Floor division >>>9//2  will give o/p 4 not 4.5 but 9/2 -> 4.5

** Exponent e.g. x**y means x to the power y.


Operator Precedence - **>~>unary operator(-,+)>*>/>%>//
x=3+4
y=5/2
print(type(x))   --- this gives the type of the variable x
output-
<class 'int'>

print(type(y))
<class 'float'>

-------------- bool ------------------------

x=False  -- not false or FALSE

y=True  --  not true or TRUE

-------------- input/print -----------------

Get input from keyboard --- input()

input function always returns string irrespective of input provided.

name=input()
age = int(input())  -- we neet to convert string into int. Input always return the data type string.
name=input("What is your name:")  -- It prints the string (What is your name:") and store the value entered by user in the variable name.

print("Hello",name)

------------- data type conversion ----------

num=input()      --- Here num is string.

number=int(num)  --- Here num is converted to integer from string type.
number=float(num)
---------- BIFs - Built in Functions --------------
isinstance() - it returns type of the variable. E.g.- isinstance(3,int) -> True
------------------ List -----------------------
How to create list-

my_list=["hello",12.50,25,True]

print(my_list)

my_list[0]

There are two ways to access the elements of list-

1. Positive Indexing

     Index increases from 0 to n

2. Negative Indexing

     It goes from right to left. Last elemet have index -1, second lost having index of -2 and so on.
     e.g. - my_list[-1]  -- it will print True

Python have two Modules-
  1. Standard Module -- it comes installed with python. example - math module
  2. External Module -- We need to install this from external.

>>> import math
>>> math.sqrt(9)
3.0

Which of the following statements would generate the string 'fun'?
print('Python is fun'[-3:])
print('Python is fun'[-3:-1])
print('Python is fun'[-3:0]) -- this prints nothing.

--------------- If condition and Inline if --------------
x=5
if x>=0:
     print("Positive number")
else
     print("Negative number")

inline if condition:-
print("Positive number" if x>=0 else "Negative Number")  --above 4 line code is written in one line.

if x>10:
   ......
elif x==10;
   .......
else
   .....

-------------- looping condition --------------------
1. for loop
lst = ["abc@gmail.com","xyz@hotmail.com","pqr@gmail.com"]
for mail in lst:
     if "gmail" in mail:
          print(mail)
for x in range(1,10):
     print(x)

for i,j in zip(lst1,lst2):
     print(i,j)

2. while loop
password = ''
while password != 'python123':
    password = input("Enter password: ")
    if password == 'python123':
        print("You are logged in!")
    else:
        print("Please try again.")

----------- File Handling --------------------
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

Different modes to open a text file-
r = read only, File pointer is placed at the beginning of the file.         
r+ = read + over-write, file pointer is placed at the beginning of the file.       
w = write only,  If the file does not exists it creates a new file.    
w+ = read + write     It deletes the file content when opened and then used to write on the file.
a = append,    
a+=read + append (Pointer is at last of file)
b = binary mode

f.read(size) -- read a file and prints 'size' number of starting character in the file.
f.read() --  will read entire file in one shot and will will return an empty string ('').
f.readline() -- it reads a single line from the file. it adds '\n' in the end of string and if the end of the file is reached the it returns a blank line.
f.write(string) -- writes the contents of string to the file, returning the number of characters written.
f.tell() -- returns an integer giving the file object’s current position.
f.seek(offset, from_what) -- takes the file current position to offset in reference to from_what position. If from_what position is not provided then it takes default 0.
f.seek(offset) --

with statement
when file is opened with 'with' statement, the file.close() part is taken care by the with statement itself. It is always best practice to use the with statement while opening the file.
example:-
with open('example.txt','a+') as file:
     file.write("Hello Mukesh")

We need not to write the file.close(), it is taken care by the with statement itself.

Thursday, May 12, 2016

Basic puzzle questions in C :: MUST KNOWN concepts to every programmers

Basic puzzle questions in C :: MUST KNOWN concepts to every programmers
Please try the below puzzles, which are very basic and also very useful in clearing the concept. Find the answer of all the puzzles in last page.

What will be the output of C puzzles below :-
Q 1>
#include<stdio.h>
int main()
{
  char *p=(char *)malloc(sizeof(char)*4); p="abc";
   char q[]="abc123";
     if(p[0]=q[0])
   {
       printf("%c, %c\n",*p,*q);
   }
}

Q 2>
#include<stdio.h>
int main()
{
  char *p=(char *)malloc(sizeof(char)*4); p="abc";
   char q[]="abc123";
     if(q[0]=p[0])
   {
       printf("%c, %c\n",*p,*q);
   }
}


Q 3>
main(){
    int num[] = {1,4,8,12,16};
    int *p,*q;
    int i;
    p =  num;
    q = num+2;
    i = *p++;
    printf("%d, %d, %d\n",i, *p, *q);
}

Q 4>
main(){
char *a[4]={"jaya","mahesh","chandra","swapant"};
int i = sizeof(a)/sizeof(char *);
printf("i = %d\n", i);
}

Q 5>
void fun(int *a, int *b)
{
 int *t;
 t=a;
 a=b;
 b=t;
printf(%d, %d\n",*a, *b);
}
main()
{
     int a=2;
     int b=3;
     fun(&a,&b);
     printf(%d, %d\n",a, b);
}

Q 6>
main(){
    int i =0;
    i = 2+3, 4>3, 3;
    printf("%d", i);
}

Q 7>
main(){
    printf("%u", -1);
}

Q 8>
struct ABC{
    float a:10;
    int b:6;
    char c;
} structure;
int main(){
    int i = sizeof(struct ABC);
    printf("%d", i);
}

Q 9>
#include<stdio.h>
int main() {
    char x[] = "abc";
    char *y = x;
    *y ='1';
    printf("%s",y);
}

Q 10>
main(){
    int i =0;
    i = 4>3, 2+3, 3;
    printf("%d", i);
}

Q 11>
#include<stdio.h>
void fun(int str,...);
int main()
{
    fun(6,"Hello","World","5","6","7","8");
    return 0;
}
void fun(int str,...)
{
    int i;
    int *n=&str;
    for(i=1;i<=str;i++)
    printf("%s ",*(n+i));
    return 0;

}

ANSWERS::
1> Segmentation Fault
   Reason-> We can't assign value to pointer valriable like this.
Different ways to assign value to pointer valriable. 
char *p="Hello World";
char *p=new char[11];  p="Hello World";
Wrong ways which lead to segmentation fault::
p[0]='a'; if(p[0]=='a'){};  *p='a'; if(*p=='a'){};
2> a, a

3> 1, 4, 8

4> 4

5> 3, 2
   2, 3
6> 5
   Explanation:: It stores only the first value.

7> 4294967295   :: As the size of unsigned int is from 0 to 4,294,967,295. -1 will print the back side of zero i.e. 4294967295.

8> Compilation Error:: We cannot use but filed for Float.

9> 1bc

10> 1  ::4>3 return 1 as it is true.

11> Hello World 5 6 7 8


Please comment if you find any thing wrong also please post the questions which you feel need to be shared.

Saturday, November 9, 2013

Doubly linked list (JAVA)

import java.io.*;
class node
{   int data;
    node next;
    node prev;
    node(int d)
    { data=d; }
}

class link
{   private node first;
    private node last;
    public link()
    {  first=null;  last=null;  }
   
    public void insfirst(int a)
    { node newnode=new node(a);
      newnode.next=first;
     
 
   
      first=newnode;
    }
    public void delfirst()
    { if(first==null)
        {   System.out.println("UNDERFLOW");  }
      else
      {  first=first.next;  }
    }
     
  public void insafter(int b,int c)
  { node ptr; ptr=first; node newnode=new node(c);
    while(ptr.next.data!=b)
    { ptr=ptr.next; }  
    if(ptr.data==b)
    { newnode.next=ptr.next;
        newnode.prev=ptr;
        ptr.next.prev=newnode;
        ptr.next=newnode;
    }
    else
    { System.out.println("No. is not found in the list");  }
  }
 public void delafter(int b)
 {  node ptr=first;
    if(first==null)
    { System.out.println("Underflow");  }
    else
    { while(ptr.data!=b)
      ptr=ptr.next;
      if(ptr.next.data==b)
      { ptr.next.next.prev=ptr;
        ptr.next=ptr.next.next;
      }
      else
      {  System.out.println("Data is not found"); }
    }
  }
  public void display()
  {  node ptr;  ptr=first;
      while(ptr!=null)
      {  System.out.println(+ptr.data); ptr=ptr.next; }
  }
 }
 
  class doublylinkedlist
  {
 
 
    public static void main(String args[])throws IOException
    {   int x;  link mm=new link();
       try{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        do
        { System.out.println("*********DOUBLY LINKED LIST::OPTIONS********");
           System.out.println("1.>Insert first\n2.>Delete first\n3.>Insert after\n4.>Delete after\n5.>Display\n6.>Exit");
  System.out.println("Enter your option here::");
  x=Integer.parseInt(br.readLine());
  switch(x)
  { case 1:   System.out.println("Enter the node data");
              int y=Integer.parseInt(br.readLine());
              mm.insfirst(y);
              break;
    case 2:  mm.delfirst();   break;
    case 3:  System.out.println("Enter the position value and new node value");
              int l=Integer.parseInt(br.readLine());
              int m=Integer.parseInt(br.readLine());
              mm.insafter(l,m);  break;
    case 4:  System.out.println("Enter the value to be deleted");
              int n=Integer.parseInt(br.readLine());
              mm.delafter(n);  break;
    case 5: mm.display();  break;
    case 6: System.out.println("By"); break;
    default: System.out.println("Try again");
  }
  }
  while(x!=6);
 }
  catch(Exception e){ System.out.println("---->"+e);}

 }
 }            

Binary Tree (JAVA)

import java.io.*;
class node
{ int data;
node lc;
node rc;
node(int d)
{ data=d; }
}
class link
{ node root;
node ary[]=new node[20];  int top;
public link()
{ root=null;
top=1;  ary[top]=null;
}
public void insert(int a)
{ node ptr=root;
node newnode=new node(a);
if(ptr==null)
root=newnode;
else
{
 while(ptr!=null)
 {
   if(a>ptr.data)
   ptr=ptr.rc;
else if(a<ptr.data)
ptr=ptr.lc;
else
{ System.out.println("Data allredy exist");    break; }
  }
}
if(ptr==null)
ptr=newnode;
}
public void display()
{ node ptr=root;
System.out.println("INORDER");
inorder(ptr);

}
void inorder(node n)
{
if(n!=null)
{
inorder(n.lc);
System.out.println(""+n.data);
inorder(n.rc);
}
}


public void delete_lowest()
{ node ptr=root;   node parnt=null;
while(ptr.lc!=null)
{ parnt=ptr;
ptr=ptr.lc;
}
parnt.lc=null;
}
public void delete_highest()
{ node ptr=root;   node pt=null;
while(ptr.rc!=null)
{ pt=ptr;
ptr=ptr.rc;
}
pt.rc=null;
}
public void search(int x)
{ node ptr; ptr=root;
while(ptr!=null)
{ if(x>ptr.data)
ptr=ptr.rc;
else if(x<ptr.data)
ptr=ptr.lc;
else
{ System.out.println("Data found"); break; }
}
if(ptr==null)
{ System.out.println("Data not found"); }
}
}
class binarytree
{
public static void main(String args[])throws IOException
{ link newlink=new link();
int x; BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do
{   System.out.println("*****BINARY TREE**********");
System.out.println("1.INSERT\n2.DELETE SMALLEST \n 3.DELETE HIGHEST \n 4.SEARCH \n 5.DISPLAY \n 6.EXIT");
x=Integer.parseInt(br.readLine());
switch(x)
{ case 1: System.out.println("insert value");
int a=Integer.parseInt(br.readLine());
newlink.insert(a); break;
case 2: newlink.delete_lowest(); break;
case 3: newlink.delete_highest(); break;
case 4: System.out.println("insert value");
int b=Integer.parseInt(br.readLine());
newlink.search(b); break;
case 5: newlink.display(); break;
case 6: break;
default:System.out.println("try again");
}
}
while(x!=6);
}
}

Reverse a string(JAVA)

import java.io.*;
class node
{
node top;
node next;
char name;
node()
{}
node(char c)
{
name=c;
}
}
class link extends node
{
void push(char c)
{
node newnode=new node(c);
if(top==null)
{
top=newnode;
}
else
{
newnode.next=top;
top=newnode;
}
}
char pop()
{
node pot=top;
top=top.next;
return(pot.name);
}
}
class reverse
{
public static void main(String args[])
{
try
{
link k=new link();
char ch;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the string");
String s=br.readLine();
int l=s.length();
for(int i=0;i<l;i++)
{
char c=s.charAt(i);
k.push(c);
}
System.out.println("the reverse is   ");
for(int i=0;i<l;i++)
{
System.out.print(k.pop());
}
}catch(IOException e)
{
System.out.println(e);
}
}
}