Tuesday, December 26, 2017

Object Oriented Approach in Python

So Classes and Why do we need them

In Java it require that you write code in inside class but in Python it does not required.you can write a code inside a class but you don't have to.In Python we define a class using class keyword similar to define a function using def keyword.

Let's take an complete object-oriented example:

classess.py

students =[]

class Student:

      school_name = "Abhinaw Demo"
     
      def __init__(self,name,student_id=1):
              self.name=name
               self.student_id=student_id
                students.append(self)

      def __str__(self):
            return "Student "+ self.name

     def get_name(self):
            return self.name.capitalize()
    
      def get_school_name(self):
             return self.school_name

class NewSchoolStudent(Student):

    school_name="Inheritance Abhinaw Demo"
 
    def get_school_name(self):
          return "This is inheritance"

     def get_name(self):
         original_value= supper().get_name()
          return original_value + "New School"

abhinaw= NewSchoolStudent("Abhinaw")
print(abhinaw.get_school_name())
print(abhinaw.get_name())

This demo code includes classes,adding methods to our classes,Constructor,Instance and Class Attributes and Inheritance and Polymorphism.













Lambda Functions in Python

So Lambda Functions are just an anonymous function.they are very simple just saves your space and time.they are useful in case of higher  order function.Lets take an example:

def double(a):
        return a*2

Convert to Lambda Function

double = lambda a: a*2

Friday, December 22, 2017

Generator Functions - Yield Python

So Yield is a keyword.first let's take an example.

student = []

def read_file():
        try:
              f=open("students.txt","r")
               for student in read_students(f):
                      students.append(student)
               f.close()
         except Exception:
                print("Could not read file")

def read_students(f):
       for line in f:
              yield line

read_file()
print(students)

So what I have done is created a single function read_students and what it does
it iterated over the file and yield the single line from that file.

Opening,Reading and Writing Files Python

Let's save our data in a file and read from that file again when we re-open our app.
So let's take an example:

Let's take an example:

students =[]

def get_students_titlecase():
       students_titlecase = []
        for student in students:
           students_titlecase .append( student["name"].title())

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

def add_student(name,student_id=1):
        student ={"name:name", "student_id": student_id}
         students.append(student)

def save_file(student):
       try:
            f=open("students.txt","a")
            f.write(student + "\n")
             f.close()
       except Exception:
             print("Could not save")
       
def read_file():
       try:
             f=open("students.txt","r")
              for student in f.readlines():
                      add_student(student)
                f.close()
         except Exception:
              print("Could not read file")

read_file()
print_students_titlecase()

student_name=input("Enter student name: ")
student_id= input("Enter student ID: ")

add_student(student_name,student_id)
save_file(student_name)

where a= append some text
             r = reading text file

So when you run the program.the output will be something like this

Output:

Could not read file
[]
Enter student name:

Nested Functions and Closures in Python

Let's take an example:

def get_students():
      
       students=["Abhinaw","Aman"]

def get_students_titlecase():

       students_titlecase = []

       for student in students:
              students_titlecase.append(student.title())
     
        return student_titlecase

students_titlecase_names=get_students_titlecase()

print(students_titlecase_names)

This is called Nested function and basically the inner function can access the outer students So this is called closures.

Create a simple python console app

Let's create an app where user will provide the student name and Student I'd from the console.

eg: student.py

students =[]

def get_students_titlecase():
       students_titlecase = []
        for student in students:
           students_titlecase = student["name"].title()

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

def add_student(name,student_id=1):
        student ={"name:name", "student_id": student_id}
         students.append(student)

student_list = get_students_titlecase()

student_name=input("Enter student name: ")
student_id= input("Enter student ID: ")

add_student(student_name,student_id)
print_students_titlecase()

So in console you have to something like this and output will be

Enter student name: Abhinaw
Enter student ID:3455
Abhinaw

this is very simple Python app taking console input and also we can modify the program.

Thursday, December 21, 2017

Functions Arguments in Python

            Functions Arguments

So argument is parameters where you can  provide the values to functions and also useful in case you don't have to make variable global.So let's modify our existing code for input argument.

functions.py :

students = []

def get_students_titlecase():
        student_titlecase = []
        for student in students:
                students_titlecase = student.title()
          return students_titlecase

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

def add_student(name) :
        students.append(name)

student_list = get_students_titlecase()

add_student("Abhinaw")

So now modify our add_student method:

def add_student(name,student_id=332)

        students.append(name)

So here you will notice student_id=332 is basically a default or optional student_id if any user does not provide student_id then it will add the value automatically but if any user provides then in that case it will be overridden by the userinput value.

Now let's add student Dictionaries to our add_student method:

def add_student(name , student_id=222)
        student = {"name:" name, "student_id", student_id}
       students.append(student)

So call this function like this

add_student(name="Abhinaw" , student_id=14)

In Python there can be multiple variable arguments such as inbuild print function.

print("hello", "World", 34, None , "Wow')

you must have question here like how come it possible let me create our own function just to cater above.

def var_args(name, *args)
        print(name)
         print(args)

just to call the function

var_args("Abhine","Android Developer",None, True)

you can add any number of argument.

There is also a concept called kwargs.
let's have a look.

def var_args(name,**kwargs):
print(name)
print(kwargs["description"],kwrgs["feedback"])

var_args("Abhinaw" ,description="Loves Android", feedback=None,androidcodingworld_subscriber=True)

it is called kwargs argument and defined with **kwrgs.So it is not a list it is Dictionaries thats where it differs from above example.

basically it was an example of variable arguments you can add as much as you can in the form of list or can also make it  Dictionaries.


Functions in Python

                     Functions

A functions is a block organized and re-usable code and use to perform certain action.Pyhthon comes with lot of built in functions such as

print("hello world")

str(3) == "3"

int("5") == 15

username = input("Enter the user's name: ")

So now let's create our own functions.So for this you can use PyCharm editor I will provide the code here and you can run it directly using pycharm.

functions.py :

students = []

def get_students_titlecase():
        student_titlecase = []
        for student in students:
                students_titlecase = student.title()
          return students_titlecase

def print_students_titlecase():
       students_titlecase = []
       for student in students:
       students_titlecase=student.title()
       print(students_titlecase)

def add_student(name) :
        students.append(name)

student_list = get_students_titlecase()

add_student("Abhinaw")

So actually I have by knowingly added some repeated code in functions which can be removed.Lets see

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

So if you write functions for single responsibility then it will be very helpful to write Unit Testing cases and code will be organized too.

Other Data Types in Python

We went over some data types such as integers,strings,floats.ther are more types in python.i will give breife over view then.

For numbers we have gone through integers and float.we also have type called complex which denotes complex numbers.So other types are

complex
long # only in Python 2
bytes and bytearray

tuple = (3, 5, 1 ,"Abhinaw") similar to list but immutable.cannot change there values.

set and frozenset

set([3,2,3,1,5]) == (1,2,3,4,5)

So I tried to represent all data types but remember there are many things which I have not mentioned but in my next post .I will create Python app and provide source code.

Friday, December 15, 2017

Exceptions in Python

Exceptions are event occurred during your program execution.that normally cause your program to stop actually.it usually means some error has been encountered.And your program simply does not know how to deal with it.So take an example of exception code.

eg:

student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

last_name = student["last_name"]

Output:
KeyError: 'last_name'

To handle this scenario grecfully.we use try and except blog to handle this code.
So let's take another example with exception handled.

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

try:
      last_name = student["last_name"]
except KeyError:
      print("Some error occurred")

print("this code executed!!!!")

Output:

Some error occurred
This code executed!!!

Note both try and except block can have more than one line of code.
There can be many error occurred  like TypeError.Can be many other too.

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except KeyError:
      print("Some error occurred")

print("this code executed!!!!")

Output:

TypeError unsupported operand types .if you have noticed  this code executed! does not execute because we are only catching KeyError.So let's take another example.

eg:

student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except KeyError:
      print("Some error occurred")
except TypeError:
      print("I can add multiple together")

print("this code executed!!!!")

Output:

I can add multiple together
This code executed!!!

you can also generic exception like

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except Exception:
      print("Some error occurred")

print("this code executed!!!!")

And you can also add finally at the end of except block.

Python Dictionaris

So Dictionary allows me to store key-value pair of any data very easily.if you have used JSON in the past then you will be very familiar with the Dictionary in Python.

for example:

student = {

        "name": "Abhinaw"
        "student_id": 20042343
        "feedback": None
}

this is what dictionary looks like in Python.So it has key and value And the value can be of any type.Dictionaries are very helpfull in case ,when you want to store some kind of structured data.

   List of Dictionaries

all_student = [

    {"name:" "Abhinaw" ,"student_id": 20042343},
     {"name:" "Rajat" ,"student_id": 20042345},
{"name:"Gaurav" ,"student_id": 20042893},

]

      Dictionary Data

student["name"] == "Abhinaw"

suppose if you are using key which does not exists in the Dictionary then it will raise an exception called "KeyError" like

student["last_name"] == KeyError

but you can set the default value if key is not present like this

student.get("last_name", "Unknown") == "Unknown".

in case you do not find the last_name in the Dictionary.

if you want all keys in the Dictionary you can simply do like this

student.keys() =["name" ,"student_id" , "feedback"]

student.values() = ["Abhinaw" , 20042343,None]

Similarly you can delete like this

student["name"] = "James"
del student["name"]

While Loops in Python

So while loop is theoretically same like other programming language.take an example in Python.

x =0

while x < 10:

        print("Count is {0}".format(x))
         x+=1

        Infinite Loops

num =10

while True:
       if num == 42:
        break

   print("Hello World")

Wednesday, December 13, 2017

break and continue in Python

So break and continue theoretically same as other programming language.taking a small example to demonstrate both in Python.

break example:

student_names = ["james" ,"Mark", "Abhinaw", "Arudhra" ,"Rajat", "Gaurav"]

for name in student_names:
       if name == "Arudhra":
             print("Found him!" + name)
              break
         print("Currently testing " + name)

Output:

Currently testing james
Currently testing Marks
Currently testing Abhinaw
Found her! Arudhra

continue example:

student_names = ["james" ,"Mark", "Abhinaw", "Arudhra" ,"Rajat", "Gaurav"]

for name in student_names:
       if name == "Arudhra":
             print("Found him!" + name)
              continue
         print("Currently testing " + name)

Output:

Currently testing james
Currently testing Marks
Currently testing Abhinaw
Currently testing Rajat
Currently testing Gaurav

we see that except for Arudhra .it print all names.

Loops in Python

Loops: let's take a example of list.

eg: students_names = ["Abhinaw", "Aman", "Ashish", "Himanshu']

if you want to print single element then

print(student_names[0])

is fine but print every element of list we need some kind of loop.

There are two main loops in Python for loop and while loop.lets have a for loop example.

for name in student_names:

       print("Students name is {0}" .format(name))

So it will print all the elements of list student_names.Simply name is a variable.

other programming for loop:

for(var i=0; I<someArray.length; I++)
{
   var element=someArray[i];
   console.log(element);
}

However this is not the case with the Python.this is not the way Python for loop works.pyhton does hide many things.it automatically assumes that you want to start from the first element from the list and also it knows when to stop.Pyhton does not have foreach loop.

        range function

let's have an example.

x =0
for index in range(10):
       x+=10
        print("The value of a is {0}".format(x))

output will be

The value of a is 10
The value of a is 20
The value of a is 30
The value of a is 40
The value of a is 50
The value of a is 60
The value of a is 70
The value of a is 80
The value of a is 90
The value of a is 100

So whats the range function do.basically it takes a range value and kind of converts  it in list.it will execute 10 times.So in this case the index will be the element of the list.So if you don't want to start your for loop to start from 0 then range function also supports two argument like this

range(5,10)
in this case index value will be

[5,6,7,8,9]

And also if you want to increment the index value by 2 every time it execute it also supports such as

range(5,10,2)

in this case 2 denots the increment.So our list will be

[5,7,9]

you can also exit the loop in between based on some logic using break and continue.

Tuesday, December 12, 2017

Lists in Python

So Lists,some time we want to form multiple objects under a single variable name.To define a list in python.you have to do something like this.

eg:
student_names = []

simple you have created empty student names list.if you want to add some student names then simple replace empty brackets like this

student_names = ["Abhinaw", "Rajat', "Gaurav", "Babli"]

now our list has 4 string elements.In order to access the names from list we use something called index staring from 0.
eg:

student_names[0] == "Abhinaw"
student_names[2] == "Gaurav"

So suppose you want to get last element from the list.then you have to do something like this.

student_names[-1] == "Babli"

So actually this gives the first element from right side of the list.In Python just remember there is no such thing negative zero.

                  List Functions

suppose you want add some names to list then you have to do like this.

eg:

student_names = ["Abhinaw", "rajat", "Gaurav"]

student_names[3] = "Babli" # No can do!

student_names.append("Babli") # Add to the  end

So now list will be:

student_names == ["Abhinaw", "rajat", "Gaurav", "Babli"]

*if you want to check the name already exist or not

eg:

"Abhinaw" in student_names == True

# Abhinaw is still there

*check how many elements in the list
eg:

len(student_list) == 4

Note: if you have noticed in Python we have never tell that it is list of string.So this is added advantage with the Python over other programming language.

    Delete element from List

eg:

students_names = ["abhinaw", "rajat", "Gaurav"]

del student_names[2]

this will delete 2nd element from list
which is "Gaurav" .Now the whole list will be going to shift after this operation.

                       List Slicing

student_names = ["Mark" ,"Katarina" ,"Homer"]

let say we want to ignore the first element which is "Mark" and get all other.

student_names[1:] == ["Katarina", "Homer"]

student_names[1:-1] == ["Katarina"]
Note this will not modify the list.list will be same it is just a temporary ignoring certain elements.

there are many more operations you can perform like reverse and pop etc.




If Statements in Python

If Statement is very simple in Python.Let me give you an example.

number = 5
if number == 5:
       print("Number is 5")
else:
       print("Number is NOT 5")

Remember one thing Python uses indentation rather than curly braces for any code blocks.notice that there is colon(:) at if and else both.this is required in python.we use == equal sign to check the  equality in Python.

in Python there is a concept of "Truthy and Falsy Values" for example.

number=5
if number:
 
     print("Number is defined and truthy")

text = "Python"
if text:
   
    print("Text is defined and truthy")

In many other programming language you have to check the length of the variable if it is value greater or less than zero but in Python you could just write like above.

okay in case of Boolean and None:it also has Truthy and Falsy Values.
eg:

pyhton_course = True

if python_course :

# Not python_course == True

    print("this will execute")

aliens_found = None

if aliens_found :
    print("This will NOT execute")

you can also set the same thing for None like I have done above.

               Not If

number = 5

if number !=5 :
      print("this will not execute")

python_course = True

if not python_course:

     print("this will also not excute")

Multiple If Conditions

number = 3

python_course = True

if number  == 3 and python_course:
   
    print("this will execute")

if number == 17 or python_course :

   print("this will also execute")

Note: in Python there is no && or || for and  and or like in other programming language.

           Ternary If Statements

a = 1
b = 2

"bigger" if a>b else "smaller"

This is called Ternary if Statement in Python.

Boolean and None in Python

As you know about boolean in other programming language. it is same in python too but with small differences .boolean can be  a true or false value.can be declared as either of them.

eg:

python_course = True
java_course = False

Simply type a name and assign a value "True" or False .

if you have noticed only difference with other programming language is that it starts with Capital letter T for True and Capital letter F for False .interestingly you can convert Boolean value to int and it will give you values 1 and 0 in case of True and False like below.

eg:

int(python_course) == 1
int (java_course) == 0
str(python_course) == "True"

And for string it will simply give textual representation "True" or "False".

Now coming to None: it is similar to null like other programming languages.

eg:

aliens_found = None

I find it useful as a place holder variable.Something that I will use later.However there is difference between variable you have defined None and other the  variable not defined at all.
Simply type k in idle and idle will tell you that k has not been defined but if I assign None to k then it will not give any result but normal for None and also it will not cause any error to show either.So None is called None type.

Monday, December 11, 2017

Strings in Python

We use string to represent text.by default it's Unicode text in Python 3 but ASCII text in Python 2.And this is one of  the big advantage in Python 3 by the way.Strings can be defined like below:

eg:

'hello world' == "Hello World" == " " "Hello World " " "

There is absolutely no difference which one you use.you can write multi-line string using 3 double quotes but this string  is not going to assign to any variable.it just to be sitting there as a comment.your editor will recognize it.it is a comment.Definning String is very simple just type a variable name and assign it a textual value  and done.
String in Python supports lot of utility methods.some of them are:

eg:

"hello" .capitalize() == "Hello"
"hello".replace("e" , "a") == "hallo"
"hello" .isalpha() == True
"123".isdigit() == true # Usefully when converting to int

"some ,CSV,values" .split(",") == ["Some" , "CSV" , "Values"]

String Format Function-

normally, use when you want to replace existing text in a given string with a variable value.

For example:

name = "pyhthonBO"
machine = "HAL"

Let's print it like this:

"Nice to meet you {0}.I am {1}".formate(name,machine)

So you must be thinking it of bit weird.So let me tell you here {0} and {1} meaning.
{0} represents the variable name argument position in format function.
you can add many argument to the formate function.
python 3.6 introduces string interpolation though So now you can do some thing like

f"Nice to meet you{name}.I am {machine}"

you can also pre-fix with r and u before the string.to deal with raw and Unicode text.its up to you.what you choose.
There are many other string properties like slicing and cutting etc.

Integers and Floats in Python

Defining integers in Python is very easy.
eg:
answer=42

pi=3.14159

Python 3 also introduces complex numbers as a type.There is no real need to worry about types in Python.atleast not in the beginning.

answer + pi = 45.14159 # Don't worry about conversion !

you can seamlessly add integers, float .pyhton does not complain about it.it will produce desired results.And to cast anything.just have to do something like this.

int(pi) == 3
float(answer) == 42.0

this is needed when we really want to cast the integer and float variables.

Thursday, December 7, 2017

Types in Python

In Python type has been handled differently than other programming languages.in many programming languages including JAVA or C# .you have to declare variable type before you declare variable itself.that variable type can be int,float,double, String,char Boolean or your own custom types such as Student.So before you even declare variable you have to write something like this.

// C# or java

int answer=42;
String name="Pyhton";

With pyhton take this approach in opposite direction.in pyhton it is not necessary  to declare type anywhere.in fact you will do something like this.

# Python

answer = 42
name = "Python'

And same thing goes with other types including your own type.
Now there are some advantages and disadvantages of this approach.
Pyhton also called dynamically typed language.So not declaring types leads many bugs for example suppose we have simple function they just adds two numbers.will look like below.

def add_numbers(a,b)
print(a+b)

Call the function
add_numbers(5,11)
16. everyhting is fine.

but what if we call like below:

add_numbers(5,"something")

It will give type error:unsupported operand types.
well python does not have any machenism to tell you in advance while other languages have.

There is something called "type hinting".

Type Hinting: this is new features added in Python version 3.5 .they will help you to add data types in your program.it will help your IDE.it will not prevent your wrong  code running.So you can do something like this:

def add_numbers(a: int, b: int)  -> int:
return  a + b

Installing PyCharm

Although we have started using IDLE for python.now we will use PyCharm integrated Developer environment.this is excellent IDE and this is built by the same forks who brought  IntelliJ ide.They have a free community edition for PyCharm available for download from there Website.
If you don't want to use PyCharm don't use it. any text editor will work fine including notepad.for the purpose I will certainly give all tutorials using PyCharm.

To download it simply go to"www.jetbrains.com/pycharm/" then click on the "Download Now" button and then "Download" free community edition of PyCharm.once you download and install PyCharm.click "Create New Project" and make sure that "Pure Python" is selected.
also you can see Location and Interpreter path.if you click on Interpreter you will see all the installed pyhton interpreter on your computer. And also make sure you select Python version 3 and above.in Location path basically it's your workspace.
now click on create.then you will be able to see Pycharm IDE with some files in it.And you can also add Python files by right click on your project and select pyhton file,name it helloworld.py  and click ok and write below code.

print("Hello World") and then right click on the HelloWorld.py you will see "Run helloworld'". in consloe you will able to see Hello World .

Now your PyCharm IDE is ready to use.

The Awesomeness of the Python

One you install python.you will have a handy tool called PowerShell or python terminal.if you just type Python 3 then you will have an access of entire pyhton programming language.this is pretty much different than any other programming languages such as Java ,C and if you are a front end developer.think of this as JavaScript console in your browser developer tools.

So what it mean exactly?.

Well being able to just type Python in terminal gives you some advantages as a developer.

for example,
suppose you are not really sure about a result of a function or any other code out put.you can simply start the Python interpreter on your machine and see what happening when you used that function.Now a days many pyhton I'd is coming with integrated pyhton console.thats the same when we ran the program through our command prompt terminal.
unfortunately this also comes with a draw back every Python program we ran pre-fix it with the Python command.

let say we  have a sample program:

# hello.py
print("Hello World")

It simply prints Hello World but in order to run it we need to open terminal and write
hello.py

And you will see below output
Hello World

During development it is a distraction but now many Python I'd are coming in a single package.

Towards the end of the course I will teach you how to create one binary file from windows,Mac or Linux machine. then you can run on any operating system.as I have mentioned if you use python from command line you will have full power of python  but if you want little bit more than that such as Syntax highlighting then you will want to run the "idle" integrated development environment.
Not that this not just any IDE .this is comes installed by default.
To open it just simply search it idle and tap it,CMD will be opened . there is not much difference when you were using CMD.
The advantages of using IDLE over CMD(Command Prompt) is code completion,Syntax highlighting etc.
Very soon I will tell you about a free integrated development environment called PyCharm.

Friday, November 24, 2017

Installing Python

Well we talked much about Python. now and next logical steps is installing python.
So installing Python involves a download from pyhton website"https://www.python.org/downloads/" and as of now latest version is Python 3.6.3 released in 2017-10-03.

Once the download finished .open the setup file and remember you will see a check box at the very bottom and written like "Add Python 3.6.3 to PATH".just check it and then click on install now.
Once it is done then let's verify that Python is installed on the system or not.

using the CMD or PowerShell whicherver you prefer.

1) Search for Windows PowerShell or CMD.

2)Then type Python  --version 
if you get the message like below

Python 3.6.3

then your installation was successful.
If not then try to repeat the steps. it usually helps.

You can install Python on Windows,Mac and Linux.steps are same for Mac and windows but usually on Linux pyhton comes along. I mean it is bundled with the Linux os but one thing  can be different that it comes with Python version 2 but you can install separate Python version 3 on the Linux system.

Standard procedure for installing is same and also you can verify the Python version repeating the same steps.

For Mac OS there is another way also to install python using "www.brew.sh".
just search it on Google and I am sure you will get the link and using it you can easily install python 3 on Mac OS.
now you must be thinking of it's advantages.what it's worth So it has some certain advantages during my teaching I will always be referring to be python  terminal command.

Alright our pyhton is all setup.

Python 2 vs. Python 3

Python 2 vs. Python 3:

Actually if you know anything about Python then you must be thinking of which version of Python I should use.the iternal debate.
online forums are full of speeches that you should use python 2 because of this and you should use python 3  because of that but in reality just use python 3.
Actually, pyhton 3 is facing adoption problem.it doesn't go smoothly as it should go thats why people  using Python 2 still comes bundled on many default systems.however Python 2 is going to end his life in 2020.

Python 2  vs.Pyhton 3:

Python 2 :

1)Maintained, but no new features
2)End of Life(EOL) in 2020;
3)Still default on many systems.
print " Hello World"

Python 3 :

1)New fetaures being added.
2)Unicode support by default.
3)Cleared some Pyhton 2 confusion
print("Hello World")

Minor differences from Python 2

Pyhton released in December 2008 but still facing adoption problems.There are not differences between Pyhtonh 2 and Pyhtonh 3 as far as Sytaxes are concerned.as a developer you must have noticed that in Python 2 printing hello world is different and in Python 3 is different.if tell you in more detail in Python 3 ,it is a funtion but as you can see in python 2 it is simple print and double quotes .                    

Thursday, November 23, 2017

Getting Started with Python

So Guys I am going to teach you about Python .as it is very powerful language.With Python you can build web app,desktop app,do scientific computation, creates scripts,artificial intelligence etc.
To learn Python you don't need any prior Python experience I will teach you first basics and then probably will go for live applications and advance concepts.

So now I am going to tell you first that what are the things required to write Python programs.i am going to cover the following contents.

1)Installing Python
2)Learning the Syntax
3)Developing a console app
4) creating executable files

So there are many tools and libraries,Frameworks  are available for Python such as

1)DJANGO
  for web developemnt
2)TENSORFLOW
for Artificial Intelligence
3)SCIPY
for scientific computations
4)PYQT
for cross-platform applications desktop applications.

I am also going to tell about basics of Python such as data types,functions,classes So by learning all these you can easily write programs in Python and later on we also create console applications.Python is very simple ,powerful and cross-platform language.

Why I am saying Python is so amazing .

let's have a look.using Python you can easily do automation work by writing scripts, Scientific calculation,can write cross-platform desktop applications,Android Development,Web backend adminstrative controls ,Machine Learning .

Use of Python:

1)cross platform desktop applications.
2)Website development using DJANGO and Flask frameworks.
3)Can work with sensors such as you can do home automation using Humidity sensors.

Let me show the simplicity of Python:

//java

public class HelloWorld
{
  public static void main (String args[])
  {
    System.out.println("Hello World");
  }
}

//Pyhton 3

print("Hello World")

So you can see I have to write lot just to write simple hello world program but in Python it's not.Actually python uses indentation yes pyhton uses tabs and spaces instead of curly braces.Pyhton follows PEPS.its a coding guidelines for Python.Now PEP 8 is there it usually integrated in your editor So don't worry.As of now I am not going in much details.

Continue..................

Friday, November 17, 2017

Backtracking | The Knight’s tour problem


So what is "The Knight's tour problem"?


A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once. If the knight ends on a square that is one knight's move from the beginning square (so that it could tour the board again immediately, following the same path), the tour is closed, otherwise it is open.

The knight's tour problem is the mathematical problem of finding a knight's tour. Creating a program to find a knight's tour is a common problem given to computer science students. Variations of the knight's tour problem involve chessboards of different sizes than the usual 8 × 8, as well as irregular (non-rectangular) boards.

The knight's tour problem is an instance of the more general Hamiltonian path problem in graph theory. The problem of finding a closed knight's tour is similarly an instance of the Hamiltonian cycle problem. Unlike the general Hamiltonian path problem, the knight's tour problem can be solved in linear time.

So,Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Problems which are typically solved using backtracking technique have following property in common. These problems can only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for these problems is to try all configurations and output a configuration that follows given problem constraints. Backtracking works in incremental way and is an optimization over the Naive solution where all possible configurations are generated and tried.


Naive Algorithm for Knight’s tour

The Naive Algorithm is to generate all tours one by one and check if the generated tour satisfies the constraints.

while there are untried tours
{
   generate the next tour
   if this tour covers all squares
   {
      print this path;
   }
}


Now,Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and one by one add items (Meaning of item varies from problem to problem. In context of Knight’s tour problem, an item is a Knight’s move). When we add an item, we check if adding the current item violates the problem constraint, if it does then we remove the item and try other alternatives. If none of the alternatives work out then we go to previous stage and remove the item added in the previous stage. If we reach the initial stage back then we say that no solution exists. If adding an item doesn’t violate constraints then we recursively add items one by one. If the solution vector becomes complete then we print the solution.

Backtracking Algorithm for Knight’s tour

Following is the Backtracking algorithm for Knight’s tour problem.

If all squares are visited
    print the solution
Else
   a) Add one of the next moves to solution vector and recursively
   check if this move leads to a solution. (A Knight can make maximum
   eight moves. We choose one of the 8 moves in this step).
   b) If the move chosen in the above step doesn't lead to a solution
   then remove this move from the solution vector and try other
   alternative moves.
   c) If none of the alternatives work then return false (Returning false
   will remove the previously added item in recursion and if false is
   returned by the initial call of recursion then "no solution exists" )
 
   Following are implementations for Knight’s tour problem. It prints one of the possible solutions in     2D matrix form. Basically, the output is a 2D 8*8 matrix with numbers from 0 to 63 and these   numbers show steps made by Knight.
   
Sample program:
 
 
class KnightTourTest
{
static int N = 8;
static boolean isSafe(int x, int y, int sol[][])
{
return (x >= 0 && x < N && y >= 0 &&
y < N && sol[x][y] == -1);
}

static void printSolution(int sol[][])
{
for (int x = 0; x < N; x++)
{
for (int y = 0; y < N; y++)
System.out.print(sol[x][y] + " ");
System.out.println();
}
}
static boolean solveKT()
{
int sol[][] = new int[8][8];

for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
sol[x][y] = -1;

int xMove[] = {2, 1, -1, -2, -2, -1, 1, 2};
int yMove[] = {1, 2, 2, 1, -1, -2, -2, -1};

sol[0][0] = 0;

if (!solveKTUtil(0, 0, 1, sol, xMove, yMove))
{
System.out.println("Solution does not exist");
return false;
}
else
printSolution(sol);

return true;
}

/* A recursive utility function to solve Knight
Tour problem */
static boolean solveKTUtil(int x, int y, int movei,
int sol[][], int xMove[],
int yMove[]) {
int k, next_x, next_y;
if (movei == N * N)
return true;

/* Try all next moves from the current coordinate
x, y */
for (k = 0; k < 8; k++) {
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol)) {
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1,
sol, xMove, yMove))
return true;
else
sol[next_x][next_y] = -1;// backtracking
}
}

return false;
}

public static void main(String args[]) {
solveKT();
}
}

Output:

0 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12

Note that Backtracking is not the best solution for the Knight’s tour problem. 


  

Backtracking question asked in Samsung and Amazon - Write a program to print all permutations of a given string.

Backtracking question asked in Samsung and Amazon - Write a program to print all permutations of a given string.

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.

Below are the permutations of string ABC.

ABC ACB BAC BCA CBA CAB

Solution based on backtacking:



Sample Program:


public class PermutationTest
{
public static void main(String[] args)
{
String str = "ABC";
int n = str.length();
PermutationTest permutation = new PermutationTest();
permutation.permute(str, 0, n-1);
}
private void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}

public String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}

}

Output:

ABC
ACB
BAC
BCA
CBA
CAB


Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a a permutation.

Note : The above solution prints duplicate permutations if there are repeating characters in input string.



Thursday, November 16, 2017

Dynamic Programming | Matrix Chain Multiplication

Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.

We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same.

For example, if we had four matrices A, B, C, and D, we would have:

 (ABC)D = (AB)(CD) = A(BCD) = ....

 However, the order in which we parenthesize the product affects the number of simple   arithmetic operations needed to compute the product, or the efficiency.

 For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,

 However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency.

 For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,

    (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations
    A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations.
   
   
 Clearly the first parenthesization requires less number of operations.

Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain.

  Input: p[] = {40, 20, 30, 10, 30}  
  Output: 26000
 
  There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.
  Let the input 4 matrices be A, B, C and D.  The minimum number of
  multiplications are obtained by putting parenthesis in following way
  (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30

  Input: p[] = {10, 20, 30, 40, 30}
  Output: 30000
 
  There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30.
  Let the input 4 matrices be A, B, C and D.  The minimum number of
  multiplications are obtained by putting parenthesis in following way
  ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30

  Input: p[] = {10, 20, 30}
  Output: 6000
 
  There are only two matrices of dimensions 10x20 and 20x30. So there
  is only one way to multiply the matrices, cost of which is 10*20*30
 
  So now see it how?
  
  1) Optimal Substructure:
 
A simple solution is to place parenthesis at all possible places, calculate the cost for each placement and return the minimum value. In a chain of matrices of size n, we can place the first set of parenthesis in n-1 ways. For example, if the given chain is of 4 matrices. let the chain be ABCD, then there are 3 ways to place first set of parenthesis outer side: (A)(BCD), (AB)(CD) and (ABC)(D). So when we place a set of parenthesis, we divide the problem into subproblems of smaller size. Therefore, the problem has optimal substructure property and can be easily solved using recursion.

Minimum number of multiplication needed to multiply a chain of size n = Minimum of all n-1 placements (these placements create subproblems of smaller size)

2) Overlapping Subproblems:

Following is a recursive implementation that simply follows the above optimal substructure property.

Sample Program:

class MatrixChainMultiplicationTest
{

static int MatrixChainOrder(int p[], int i, int j)
{
if (i == j)
return 0;

int min = Integer.MAX_VALUE;

for (int k=i; k<j; k++)
{
int count = MatrixChainOrder(p, i, k) +
MatrixChainOrder(p, k+1, j) +
p[i-1]*p[k]*p[j];

if (count < min)
min = count;
}

return min;
}

public static void main(String args[])
{
int arr[] = new int[] {1, 2, 3, 4, 3};
int n = arr.length;

System.out.println("Minimum number of multiplications is "+
MatrixChainOrder(arr, 1, n-1));

}
}

Output:

Minimum number of multiplications is 30

Time complexity of the above naive recursive approach is exponential.
It should be noted that the above function computes the same subproblems again and again.





Wednesday, November 15, 2017

Top Common Mistakes Done by Android Developer

Top Common Mistakes Done by Android Developer

Android. What’s not to like about this platform? It’s free, it’s customizable, it’s rapidly growing and it’s available not just on your phone or tablet, but on your smartwatch, TV and car too.

With the latest Oreo update, Android programming continues to improve. The platform has matured quite a bit since the initial AOSP release, and set the user expectations bar quite high.

There are thousands of different devices, with different screen sizes, chip architectures, hardware configurations, and software versions. Unfortunately, segmentation is the price to pay for openness, and there are thousands of ways your app can fail on different devices, even as an advanced Android programmer.

Regardless of such huge segmentation, the majority of bugs are actually introduced because of logic errors. These bugs are easily prevented, as long as we get the basics right!.

I am gone tell all those mistakes which you can avoid while development.

1) Developing for Your Android Device:

Unless you are building a kiosk/promo app for a single tablet, chances are your Android app won’t look good on every device. Here are a few Android programming tips to remember:

Density-independent pixels (dp) are different than normal pixels (px).
Resources are included multiple times to account for different densities and orientations.
9-patch drawables are stretched to fit the screen.
There are literally thousands of possible scenarios, but after a while you develop a sense for covering them all with a handful of cases.

You don’t own thousands of devices? Not a problem. The Android Emulator is super good in replicating physical devices. Even better, try out Genymotion, it’s lightning fast and comes with a lot of different popular preset devices.

Also, have you tried rotating your device? All hell can break loose…

2)Not Using Intents:

Intents are one of Android’s key components. It’s a way of passing data between different parts of the app or, even better, different apps on the system.

Let’s say you have a gallery app that can share a download link to some images via SMS. Which of the two options seems more logical?

Option 1:

Request the SEND_SMS permission.

  <uses-permission android:name="android.permission.SEND_SMS" />
 
Write your own code for sending SMS using the SmsManager.
Explain to your users why your gallery app needs access to services that can cost money, and why they have to grant this permission to use your app.

Option 2:

Start an SMS Intent and let an app designed for SMS do the work

  Intent sendIntent = new Intent(Intent.ACTION_VIEW);
  sendIntent.setData(Uri.parse("sms:" + telephoneNumber));
  sendIntent.putExtra("sms_body", x);
  startActivity(sendIntent);
 
In case that you have any doubts, best solution is option 2!

This approach can be applied to almost anything. Sharing content, taking pictures, recording video, picking contacts, adding events, opening links with native apps, etc.

Unless there is a good reason to make a custom implementation (ex., a camera that applies filters), always use Intents for these scenarios. It will save you a lot of programming time, and strip the AndroidManifest.xml of unnecessary permissions.

3)Not Using Fragments:

A while ago in Honeycomb, Android introduced the concept of fragments. Think of them as separate building blocks with their own (rather complex) life cycles that exist inside an Activity. They help a lot with optimizing for various screens, they are easily managed by their parent activity, can be reused, combined and positioned at will.

Launching a separate activity for each app screen is terribly inefficient, since the system will try to keep them in memory as long as it can. Killing one won’t free the resources used by the others.

Unless you want to dig deep into the Android core and read this article, advocating against fragment usage, you should use fragments whenever possible. It basically says that fragments and cursor loaders have good intended purpose, but poor implementation.

4)Blocking the Main Thread:

The main thread has a single purpose: keeping the user interface responsive.

Although the science behind measuring the frame rate our eyes/brain can perceive is complex and influenced by a lot of factors, a general rule is that anything below 24 fps with delay greater than 100 ms won’t be perceived as smooth.

This means that the user’s actions will have a delayed feedback, and the Android app you have programmed will stop responding. Stripping the user of his control over the app leads to frustration.

Even worse, if the main thread is blocked for a while (5 seconds for Activities, 10 for Broadcast Receivers), ANR will happen.

This was so common in Android 2.x, that on newer versions the system won’t let you make network calls in the main thread.

To avoid blocking the main thread, always use worker/background threads for:
1. network calls
2. bitmap loading
3. image processing
4. database querying
5. SD reading / writing

5)Reinventing the Wheel:

“OK, I won’t use the main thread. I’ll write my own code that communicates with my server in a background thread.”

No! Please don’t do that! Network calls, image loading, database access, JSON\xml\SOAP parsing, and social login are the most common things you do in your app. Not just yours, every app out there. There is a better way. Remember how Android has matured and grown as a platform? Here’s a quick list of examples:

Use gradle as a build system.
Use Retrofit / Volley for network calls.
Use Picasso for image loading.
Use Gson / Jackson for JSON parsing.
Use common implementations for social login.
If you need something implemented, chances are it’s already written, tested and used widely. Do some basic research and read some Android programming tutorials before writing your own code!.

6)Not Understanding Bitmaps:

Users love content! Especially when the content is well formatted and looks nice. Images, for instance, are extremely nice content, mainly due to their property of conveying a thousand words per image. They also consume a lot of memory. A lot of memory!

Before an image is displayed on the screen, it has to be loaded into the memory. Since bitmaps are the most common way to do this, we’re going to provide an Android programming guide for the whole process:

Let’s say you want to display an image on your screen that you just took with your camera. The total memory needed for this is calculated with the following formula: memory_needed_in_bytes = 4 * image_width * image_height;

Why 4? Well, the most common / recommended bitmap configuration is ARGB_8888. That means that for each pixel we draw, we need to keep 8 bits (1 byte) for the alpha, the red, the greed and the blue channel in memory, in order to properly display it. There are alternatives, like the RGB_565 configuration that requires half the memory than ARGB_8888, but loses the transparency and the color precision (while maybe adding a green tint).

Let’s assume you have a brand new device with full HD screen and 12 MP camera. The picture you just took is 4000x3000 pixels large and the total memory needed to display it is: 4 bytes * 4000 * 3000 = 48 MB

48 megabytes of your RAM just for a single image!? That’s a lot!

Now let’s take the screen resolution into consideration. You are trying to show a 4000x3000 image on a screen that has 1920x1080 pixels, in worst case scenario (displaying the image full screen) you shouldn’t allocate more than 4 * 1920 * 1080 = 8.3 MB of memory.

Always follow the Android programming tips for displaying bitmaps efficiently:

Measure the view you’re showing your images in.
Scale / crop the large image accordingly.
Show only what can be displayed.

7)Using Deep View Hierarchy:

Layouts have an XML presentation in Android. In order to draw content, the XML needs to be parsed, the screen needs to be measured, and all the elements need to be placed accordingly. It’s a resource- and time-consuming process that needs to be optimized.

This is how the ListView (and more recently the RecyclerView) works.

If a layout has been inflated once, the system reuses it. But still, inflating the layout must happen at some point.

Let’s say you want to make a 3x3 grid with images. One way of doing this is a vertical LinearLayout containing 3 LinearLayouts with equal weight, each of them containing 3 ImageViews with equal weight.

What do we get with this approach? A warning that “nested weights are bad for performance”.

There is a saying in the Android programming world, that I just made up: “With little effort all hierarchy can be flattened”.

In this case RelativeLayout or GridLayout will efficiently replace the nested LinearLayouts.

8) Not Setting the minSdkVersion to 14:

Well, this is not a mistake, but it is bad practice.

Android 2.x was a huge milestone in developing this platform, but some things should be left behind. Supporting older devices adds more complexity for code maintenance and limits the development process.

The numbers are clear, the users have moved on, the developers shouldn’t stay behind.

I’m aware that this doesn’t apply for some big markets with old devices (ex. India), and setting the minSdkVersion to 14, on the Facebook App, means leaving couple of million users without their favorite social network. But, if you are starting fresh and trying to create a beautiful experience for your users, do consider eliminating the past. Users that don’t have the resources, or feel the need to upgrade their device/OS, won’t have the incentive to try out a superior version of your Android app and ultimately spend money on it.

9) Developing App in MVC Architecture:

i have seen thousands of time that client is shouting that write unit test cases for my business logic and let me know the coverrage of it.then if your app is in MVC  then you can never say that you can write 100% unit test cases because of tight coupling between the business logic and controller and vice-versa.So instead of MVC use MVP because of its simplicity,abstractness,code maintainability,separate business logic presenter class etc.i can write 1000 of advantages over MVC which actually helps in long term project.

10) Not Giving Importance to User Experience:

Apps are made for users. so, user experience is the key factor that determines the success or failure of an app. There are several seminars, annual events and conferences help over this common topic. However, add developers often fail to place enough emphasis on this crucial factor and intuitive design.

Before finalizing an app, run usability or user acceptance testing (UAT) several times to check how it works on the mobile platform. Such testing can give you better understanding of user experience and persona, and even how people would like to interact with the app. To ensure this process works smooth and fine, wireframe the entire designing process.

11) Inefficient Resources Management in Android App Development:

Android application resources such as images, icons, layouts, text strings, etc. are vital for app performance. Due to responsive designing needs, these resources need more than one alternatives to fit in any device from tiny to large handhelds.

Therefore, an advanced architecture for resources management is essential, and we can do it by externalizing the application resources from the code. We can maintain such resources independently by creating directories and sub-directories in res/directory of your Android project.

Besides primary resources, you should place alternative resources for specific device configurations. You can group it all specifically named resources directories and sub-directories so that Android can use the appropriate resource in runtime based in its current configuration.







Tuesday, November 14, 2017

Dynamic Programming - Edit Distance


Question : Given two strings str1 and str2 and below operations that can performed on str1. Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.

Example: 

Input:   str1 = "geek", str2 = "gesek"
Output:  1
We can convert str1 into str2 by inserting a 's'.

Input:   str1 = "cat", str2 = "cut"
Output:  1
We can convert str1 into str2 by replacing 'a' with 'u'.

Input:   str1 = "sunday", str2 = "saturday"
Output:  3
Last three and first characters are same.  We basically
need to convert "un" to "atur".  This can be done using
below three operations.
Replace 'n' with 'r', insert t, insert a


So there can be many many solution for this problem but giving you the best solution:

The idea is process all characters one by one staring from either from left or right sides of both strings.

Let we traverse from right corner, there are two possibilities for every pair of character being traversed.

m: Length of str1 (first string)
n: Length of str2 (second string)

If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1.

Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations and take minimum of three values.

Insert: Recur for m and n-1
Remove: Recur for m-1 and n
Replace: Recur for m-1 and n-1

Sample Program:

class EDISTTest
{
static int min(int x,int y,int z)
{
if (x<=y && x<=z) return x;
if (y<=x && y<=z) return y;
else return z;
}

static int editDist(String str1 , String str2 , int m ,int n)
{
if (m == 0) return n;

if (n == 0) return m;

if (str1.charAt(m-1) == str2.charAt(n-1))
return editDist(str1, str2, m-1, n-1);

return 1 + min ( editDist(str1, str2, m, n-1), // Insert
editDist(str1, str2, m-1, n), // Remove
editDist(str1, str2, m-1, n-1) // Replace
);
}

public static void main(String args[])
{
String str1 = "sunday";
String str2 = "saturday";

System.out.println( editDist( str1 , str2 , str1.length(), str2.length()) );
}
}

Output: 3

Time complexity:

The time complexity of above solution is exponential.
In worst case, we may end up doing O(3m) operations. The worst case happens when none of characters of two strings match.










Tuesday, October 3, 2017

Run-time Stack mechanism in Java

Run-time Stack mechanism in Java

Ans:

For every thread that you create,JVM (Java virtual machine) creates a run-time stack.

1)Each and every call performed in a thread is stored in the stack.

2)Each entry in the run-time stack is known as activation record or stack frame.

3)After completing every method call by the thread then all the corresponding entry of the stack will be removed.

4)After completing all the methods, the stack will be empty and that run-time stack will be destroyed by the JVM before terminating the thread.

Normally:

Construction of run-time Stack : 

1. Firstly, the main thread will call main() method and the corresponding entry will be in the stack.

2. After that main() method is calling fun() method, which will store in the stack.

3. In the fun() method, moreFun() method is called. Therefore at last moreFun() will be stored in stack.

4. Finally, moreFun() is not calling any method and it will print Hello Guys!

Example:

class Test {
public static void main(String[] args)
{
fun();
}
public static void fun()
{
moreFun();
}
public static void moreFun()
{
System.out.println("Hello Guys!");
}
}

Output: Hello Guys!



Destruction of run-time stack : 

After printing Hello Guys!, its corresponding entry will be removed from the stack and it will go to fun() method and there is nothing for execution that’s why the entry of fun() method is removed from the stack and so on.When the stack is empty then the run-time stack is destroyed by the JVM.



Abnormally

Construction of run-time Stack :

1. The example below have ArithmeticException at method moreFun() location, the JVM will check any exception handling code is there. If not, then method moreFun() will be responsible to create exception object because of exception are raised on method moreFun() and corresponding entry from the stack will be removed and the control goes to method fun().

2. JVM again go to the caller method to check if it is having any exception handling code are not. If not JVM terminates the method abnormally and deleted the corresponding entry from the stack.

3. The above process continues until main thread. If the main thread(main method) doesn’t have any exception handling code the JVM also terminates the main method abnormally and default exception handler is responsible to print the exception message to the output screen which is the part of JVM.

Sample Code:

public class Test {
public static void main(String[] args)
{
fun();
}
public static void fun()
{
moreFun();
System.out.println("Method fun");
}
public static void moreFun()
{
System.out.println(10 / 0);
System.out.println("Method moreFun");
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.moreFun(Test.java:14)
at Test.fun(Test.java:9)
at Test.main(Test.java:5)





Destruction of run-time stack:







Most frequent word in an array of strings? OR Find winner of an election where votes are represented as candidate names?

Question:

Most frequent word in an array of strings?

                                                    OR

Find winner of an election where votes are represented as candidate names?

Solution:

Given an array of names of candidates in an election. A candidate name in array represents a vote casted to the candidate. Print the name of candidates received Max vote. If there is tie, print lexicographically smaller name.

               OR
Given an array of words find the most occurring word in it.

Input : arr[] = {"Abhinaw", "for", "Abhinaw", "Abhinaw",
                "portal", "to", "learn", "can",
                "be", "computer", "science",
                 "zoom", "yup", "fire", "in",
                 "be", "data"}

Output : Abhinaw

"Abhinaw" is the most frequent word as it.
occurs 3 times

So i can think of like this:

Run two loops and count occurrences of every word.

Time complexity of this solution is O(n * n * MAX_WORD_LEN).

Bu i have an another efficient solution also which is below:

Trie data structure: The idea is simple first we will insert in trie. In trie, we keep counts of words ending at a node. We do preorder traversal and compare count present at each node and find the maximum occurring word.

Time Complexity : O(n * MAX_WORD_LEN)

I have  Hashing solution also and which is more efficient solution than above.Have a look into the code.

Sample Code:

import java.util.HashMap;
import java.util.Map;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
public class MostFrequentWordOrElectricVotingApp
{
public static void main(String[] args)
{
String[] votes = { "Abhinaw", "Gaurav", "Abhishek",
"Garima", "babli", "Logesh",
"Lalitha", "Pawan", "Abhinaw",
"Abhinaw", "Garima", "Abhinaw",
"Abhinaw" };

        findWinner(votes);
}

public static void findWinner(String votes[])
       {
        Map<String,Integer> map =new HashMap<String, Integer>();
        for (String str : votes)
        {
            if (map.keySet().contains(str))
                map.put(str, map.get(str) + 1);
            else
                map.put(str, 1);
        }
        int maxValueInMap = 0;
        String winner = "";
 
        for ( Map.Entry<String,Integer> entry : map.entrySet())
        {
            String key  = entry.getKey();
            Integer val = entry.getValue();
            if (val > maxValueInMap)
            {
                maxValueInMap = val;
                winner = key;
            }

            // If there is a tie, pick the
            else if (val == maxValueInMap && winner.compareTo(key) > 0)
                winner = key;
        }
        System.out.println("Winning Candidate is :" +winner);
    }

}

 Output: 

 Winning Candidate is :Abhinaw