How to check if a date is valid or not in python

Python program to check if a date is valid :

In this tutorial, we will check if a date is valid or not usng python.

Solution :

1. Get the input from the user
2. Input should be in the form of dd/mm/yy
3. Extract the inputs in different variables
4. use ‘datetime’ module to check if the date is valid or not

Program :

import datetime

inputDate = input("Enter the date in format 'dd/mm/yy' : ")

day,month,year = inputDate.split('/')

isValidDate = True
try :
    datetime.datetime(int(year),int(month),int(day))
except ValueError :
    isValidDate = False

if(isValidDate) :
    print ("Input date is valid ..")
else :
    print ("Input date is not valid..")

The above example is compatible with python3. First, we get the date from user input as ‘dd/mm/yy’ . Using ‘split’ , day,month and year is calculated from that string. And finally, using datetime() method of datetime module, we are checking if the input string is valid date or not.

Sample Example :

Enter the date in format 'dd/mm/yy' : 12/12/2006
Input date is valid ..

Enter the date in format 'dd/mm/yy' : 12/23/2006
Input date is not valid..

Enter the date in format 'dd/mm/yy' : 30/02/2006
Input date is not valid..

Count number of digits in a number in Python

Count the number of digits in a number using python :

Using python, count the number of digits in a number. Get the input from user and print out the result. We will show you two different ways to calculate digits .

Solution 1 :

1. Take the user input , create one variable to store the count
2. Using a while loop, each time change the number to number/10 ,i.e. if the number is 132 next time it will be 132/10 = 13
3. Increment the count by one and Repeat it till the number become 0.
4. Print the count.

count = 0
number = int(input("Enter a number "))

while (number > 0):
	number = number//10
	count = count + 1

print ("Total number of digits : ",count)

Example :
For 1234 : Step :1: number = 1234 / count = 0 ,Step :2: number 1234/10 = 123/count = 1,…. Step : 4 : number 1/count = 3,Step :5: number 1/10 = 0 .On step 5, it will not enter the while loop and print the count as 3.

Solution 2 :

Instead of using a while loop , we can directly convert the integer to a string and get the length of the string :

count = 0
number = int(input("Enter a number "))

print ("Total number of digits : ",len(str(abs(number))))

‘abs’ is used to get the absolute value of a number. i.e. to handle the case even if the number is negative .

Example :

Enter a number 123
Total number of digits :  3

Enter a number -1234
Total number of digits :  4

Find average of numbers in a list using python

Calculate the average of numbers in a list using python :

In this tutorial, we are going to show you three different ways to calculate average of numbers of a list in python.We are using python3 version 3.6.1 . You can check your python3 version by running python3 –version command on a terminal.
1. We will get the inputs from the user
2. Input numbers should be entered with comma (‘,’) as a separator
3. We will create one list from the inputs .
4. To create the list, first input numbers will be splited by ‘,’ using split() method. split() returnes a list of strings of all the numbers . we will convert it all to integer using int(string) method.
5. Finally to find the average , divide the summ of all numbers by length of the list. The sum of all elements in a list is sum(list_name) and lenght of a list is len(list_name). Following is the complete program :

1. Normal method :

numberList = []
print ("Enter all numbers with ',' as separator")
numberList = [int(i) for i in input().split(',')]
print ("Average = ",sum(numberList)/len(numberList))

2. Using ‘statistics’ module :

statistics module contains mathematical statistics functions like mean, median, harmonic mean etc. We will use this module to find out the average or mean of all numbers .

from statistics import mean
numberList = []
print ("Enter all numbers with ',' as separator")
numberList = [int(i) for i in input().split(',')]
print ("Average = ",mean(numberList))

3. Using reduce :

reduce is a very useful function to work with list elements without iterating it with a loop. We can pass a lambda or rule to it and it will return the final result by doing a rolling computation on the list value. Here , we will pass one lampda x,y : x+y to reduce with the element list as argumet. It will calculate the sum of all elements of the list using the above lambda. ‘reduce’ is in ‘functools’ module.

from functools import reduce
numberList = []
print ("Enter all numbers with ',' as separator")
numberList = [int(i) for i in input().split(',')]
print ("Average = ",reduce(lambda x,y:x+y, numberList)/len(numberList))

Sample input :

Enter all numbers with ',' as separator
1,2,3,4,5,6
Average = 3.5 //using method 1
Average = 3.5 //using method 2
Average = 3.5 //using method 3

If you know any other ways to calculate the average or if you have any doubt, please leave a comment below.

Java program to find the counts of each character in a String

Java Program to find character counts in a String :

In this tutorial, we will find the count of each characters in a given string.

Solution :

1. First get the string input from the user

2. Create one hashmap with key as ‘character’ and value as ‘integer’ . Count of each character will be stored as value with key as the character.

3. Scan the string character by character

4. Check for each character : if no key equalt to the character is available in the hashmap , add one new key as the character and value as 1.

5. If key is available, increment the value by one.

 

import java.util.HashMap;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        String line;
        int value;
        Scanner sc = new Scanner(System.in);

        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        System.out.println("Enter a String :");

        line = sc.nextLine();

        for (int i=0; i<line.length(); i++){
            if(map.containsKey(line.charAt(i))){
                value = map.get(line.charAt(i));
                value ++;
                map.put(line.charAt(i),value);
            }else{
                map.put(line.charAt(i),1);
            }
        }


        for ( Character key : map.keySet()){
            System.out.println("Character : '"+key+"' Count :"+map.get(key));
        }

    }

}

 

Java Final – Final Variables, Final Methods and Final Class

”final” keyboard can be used with methods, classes and variables in Java. Each use has different meaning that we are going to discuss in details in this tutorial : final variable, final method and final class.

1. Final Variable :

final variables are variables that cannot be changed i.e. constant. It is really good practice to use final variables using uppercase letters and underscores as separator. Something as like below :

final int MY_VARIABLE = 10;

MY_VARIABLE cannot be changed after this initialization. If you want to change, you will get compile time error.

Initialize a final variable in Instance initializer block , in constructor or in static block:

Final variables that are not declared at the time of declaration are called blank final variables. But wait ..how can it be a constant without holding a value ? Yes, we need to initialize them as well. Initialization can be done either in a instance initializer block, or in a constructor .  For a final variable that is static, we should initialise it inside static block. Let’s take a look into these three different scenarios. :

public class Car {
    final int PRICE;
    final String COLOR;
    final static String OWNER_NAME;

    {
        COLOR = "black";
    }

    static {
        OWNER_NAME = "Adam";
    }

    Cars(int price) {
        PRICE = price;
    }
}

In the above example, for the class “Car”, three final variables are defined. We can change the “PRICE” variable using its constructor each time a new object will create.
Final variables are used as constants. For global constants, static final variables are used.

Final methods :

Similar to final variables, we can have final method. Means method that  cannot be changed. Behaviour of a method can only be changed by overriding it in another class. So, final methods are not allowed to override. Example :
Car.java

public class Car {
    final int WHEELS = 4;

    public final int getNoOfWheels(){
        return WHEELS;
    }
}

Van.java

public class Van extends Car {


}

Main.java

public class Main {

    public static void main(String[] args){
        Van van = new Van();
        System.out.println("no of wheels of a Van "+van.getNoOfWheels());

    }


}

In the above example we have one Car class with one final method getNoOfWheels() that returns 4 . We have created one new class ‘Van’ extending ‘Car’ . In ‘Main’ class, we are able to access the final method ‘getNoOfWheels’ from ‘van’ object. i.e. it is inheriting the method from its parent class. But if we try to override it inside ‘Van’ class, one compile-time error will be thrown mentioning that a final method cannot be overriden.

Final Class :

Final class is a class that cannot be extended i.e. it cannot be inherited. e.g. Int and Float are final classes .

public final class Car {
    final int WHEELS = 4;

    public final int getNoOfWheels(){
        return WHEELS;
    }
}

Now, if we try to create another class by extending class ‘Car’, it will show one compile time error message.

Notes on final keyword in Java :

1. Final keyword can be applied to variable,method and class in Java.
2. Final variables cannot be changed, final methods cannot be override and final class cannot be extended.
3. Final variables should be initialised always. At the time of declaration, inside constructor, inside static method (for static final variables ) or inside instance initializer block.
4. A constructor cannot be final
5. All variables declared inside interface are final
6. Using final variables, methods and classes in Java improves performance.

Kaspersky Coupons and Deals – Upto 50% off (USA) ( August 2017)

<!–more –>

Kaspersky Antivirus

Kaspersky Antivirus

Protect everything on your PC… be safe from viruses, spyware & Trojans – and stop ransomwares locking up all your file – Kaspersky Antivirus can provide you protection from each and every virus.

Kaspersky Safe Kids

Kaspersky Safe Kids

Helps you mentor your kids on device usage time… and guide them on safety – so they only access the types of website, content & apps you decide are appropriate.

Kaspersky Internet Security
up-to 50% off

Kaspersky Internet Security

Kaspersky Internet Security helps protect you from infections, ransomware, phishing & identity theft. Surf and do all online transactions safely on your Mac or PC.

Kaspersky Total Security
Save Upto 50%

Kaspersky Total Security

Everything in single pack : Guards privacy, passwords, files & photos,Boosts security when you bank & shop online
,Helps safeguard kids… online & beyond

Kaspersky Passsword Manager

Kaspersky Passsword Manager

Use Kaspersky Password Manager securely stores every password. Remember one master password and access all other passwords

Java program to check if a Matrix is Sparse Matrix or Dense Matrix

What is a sparse matrix ?

A sparse matrix is a matrix in which most of the values are zero. Similarly a matrix with maximum non-zero values is known as dense matrix. In this tutorial, we will learn how to check if a matrix is sparse or not in java.

Sparsity of a matrix :

The proportion of zero elements to non-zero elements of a matrix is called sparsity. If a matrix contains 9 zero values and 3 non-zero values, the sparsity will be 9/3 = 3 .

Checking a matrix sparse or not programatically :

To check if a matrix is sparse-matrix or not, we will count the number of zeros in the matrix. If the count is more than half of the numbers, it will be a sparse-matrix and otherwise a Dense matrix. For a matrix with ‘r’ no of rows and ‘c’ no of columns, the total number of elements will be ‘r * c’ .
Let’s take a look into the java program to find if a matrix is sparse or Dense :

import java.util.Scanner;

public class Main {

    public static void main(String[] args){
        int row = 0;
        int col = 0;

        int count = 0; //number of zero counts

        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter the row numbers for the matrix : ");
        row = sc.nextInt();

        System.out.println("Please enter the column numbers for the matrix : ");
        col = sc.nextInt();

        int[][] matrix = new int[row][col];

        for (int i =0; i
 (row*col)/2){
            System.out.println("The above matrix is a Sparse matrix ");
        }else{
            System.out.println("The above matrix is a Dense matrix");
        }

    }


}

Sample Output :

Please enter the row numbers for the matrix : 
3
Please enter the column numbers for the matrix : 
3
Please enter row no : 1
1 0 0
Please enter row no : 2
2 0 0
Please enter row no : 3
0 0 3
The above matrix is a Sparse matrix 

Java Program to convert Decimal to Binary : Java Tutorial 3

Java program to to convert Decimal to Binary Number :

In this tutorial, we will check how to convert a decimal number to binary . We will use three different methods to convert one decimal number to its binary form.

Decimal :

For denoting integer and non-interger numbers, decimal number system uses 10 different digits , 0,1,2,3,4,5,6,7,8 and 9 i.e it is a base 10 number system. Also known as Hindu-Arabic numeral system , decimal is the mostly used numeral system .

Binary :

Binary numeral system represents numeric values using 0 and 1. It is a base 2 system and each digit is known as ‘bit’.

Let’s take a look into the code :

Java program for Decimal to Binary conversion :

Method 1 : Using an array of int :

In this method, we will use one array to store all reminders . And finally iterating through the array, we will print it out :

static void convertToBinary(int no){
    int container[] = new int[100];

    int i = 0;

    while (no > 0){
        container[i] = no%2;
        i++;
        no = no/2;
    }

    for (int j = i -1 ; j >= 0 ; j--){
        System.out.print(container[j]);
    }
}

Method 2 : Using StringBuilder :

This method is similar to the previous one, but instead of using an array we will use one StringBuilder and append each reminder :

static void convertToBinaryUsingString(int no){
    StringBuilder result = new StringBuilder();

    int i =0;

    while (no > 0){
        result.append(no%2);
        i++;
        no = no/2;
    }
    System.out.println(result.reverse());

}

Method 3 : Using inbuilt method public static String toBinaryString(int i) :
If you don’t want to find out the binary representation in one line, then “Integer” class has one static method known as toBinaryString(int).Use this method directly :

System.out.print(Integer.toBinaryString(no));

Full class :

import java.util.Scanner;

public class Main {

    public static void main(String[] args){
        System.out.println("Please enter the number you want to convert : ");
        Scanner scanner = new Scanner(System.in);

        int no = scanner.nextInt();

        if(no > 0) {
            System.out.println("Binary conversion for " + no + "is :");

            System.out.println("Using Array :");
            convertToBinary(no);

            System.out.println("\nUsing StringBuilder :");
            convertToBinaryUsingString(no);

            System.out.println("\nUsing toBinaryString() :");
            System.out.print(Integer.toBinaryString(no));

        }

    }

    static void convertToBinary(int no){
        int container[] = new int[100];

        int i = 0;

        while (no > 0){
            container[i] = no%2;
            i++;
            no = no/2;
        }

        for (int j = i -1 ; j >= 0 ; j--){
            System.out.print(container[j]);
        }
    }

    static void convertToBinaryUsingString(int no){
        StringBuilder result = new StringBuilder();

        int i =0;

        while (no > 0){
            result.append(no%2);
            i++;
            no = no/2;
        }
        System.out.println(result.reverse());

    }
}

Java 8 development with Android Studio 3.0 -Part 1

Java 8 Development using Android Studio :

Using Android Studio 3.0 preview 1 and later, some subset of Java 8 language features can be used on Android projects. Some features are compatible with all API levels and some are only for API level 24 and higher. Previously for using Java8 on Android projects, jack toolchain, Retrolambda or DexGuard was used. Jack toolchain is now deprecated ( check this  post ) and the Java 8 support is moved to the default keychain. You can still use Jack or other libraries but it is advisable to migrate to the default toolchain.

Migration :

If you have a project with Jack, Retrolambda or DexGuard using Java 8, it will still work but if you want to move to default toolchain, check out below :

Migrate from Jack Toolchain :

To disable Jack Toolchain and for using the default one, remove the jackOptions block from build.gradle file :

android {
    ...
    defaultConfig {
        ...
        // Remove below jackOptions{...} block.
        jackOptions {
            enabled true
            ...
        }
    }

Migrate from Retrolambda :

For removing Retrolambda, you need to remove its dependency and “retrolambda” block from project-level and module’s build.gradle file :
Remove the below dependency line :

classpath 'me.tatarka:gradle-retrolambda:’

Remove ‘retrolambda’ block and plugin declaration:

// remove the below line 
apply plugin: 'me.tatarka.retrolambda'

// Remove this block 
retrolambda {
    ...
    // If you have arguments for the Java VM you want to keep,
    // move them to your project's gradle.properties file.
    jvmArgs '-Xmx2048m'
}

Configure Android Studio :

Change “dependencies” tab of project level “build.gradle” file to use Android plugin 3.0.0-alpha1 or higher :

dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha7’
}

Add the following block inside android{} of build.gradle file :

android{
    ….
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

What Java 8 language features and APIs you can use with Android Studio 3.0 :

You can visit the official page  for detail info , but common operations like Lambda expressions, Method references, Type Annotations are supported on all versions with some restrictions. We will look into details on next tutorials.

Disable support :

If you are facing some trouble while using Java 8 features with Android Studio, you can disable them by adding the following line to your gradle.properties file :

android.enableDesugar=false

Java 8 Lambda Expression – Java Tutorial 2

Lambda expressions in Java 8 :

Lambda expressions are introduced in Java 8. There are various reasons why lambda expression was added . I will try to explain you with a simple example how the code is without lambda expression and how it can be changed using lambda expression :

In this exmaple we will have :
1. One model class “Car” with one String property “color”
2. One interface “ICarChecker” with a function called “public boolean isValidColor(Car car)” . It will check if a car is valid or not .
3. An adapter “CarCheckerAdapter” that implements “ICarChecker” and checks for a valid color. If color is “white” then it is valid.

Following are the classes we have mentioned above :
Car.java

public class Car {
    String color;

    public Car (String colorType){
        color = colorType;
    }

    public String getColor() {
        return color;
    }
}

Interface ICarChecker.java

public interface ICarChecker {
    public boolean isValidColor(Car car);
}

Adapter CarCheckerAdapter.java

public class CarCheckerAdapter implements ICarChecker{

    @Override
    public boolean isValidColor(Car car) {
        return car.getColor().equalsIgnoreCase("white");
    }

}

Main class Main.java

public class Main {

    public static void main(String[] args){
        Car audi = new Car("white");
        Car bmw = new Car("black");

        CarCheckerAdapter adapter = new CarCheckerAdapter(){
            @Override
            public boolean isValidColor(Car car) {
                return super.isValidColor(car);
            }
        };
        
        System.out.println("Color of Audi checker result : "+adapter.isValidColor(audi));
        System.out.println("Color of bmw checker result : "+adapter.isValidColor(bmw));

    }
}

In this example, to check if a color is valid or not , we need to create one Anonymous class CarCheckerAdapter each time. Using lambda expression, we can remove this problem. Let’s see :

What is a Lambda Expression :

The syntax of lambda expression can be defined as below :

(argument) -> {body}

1. “argument” is the argument we are passing. It can be empty or non-empty. For single parameter , parenthesis are optional
2. “body” contains the statements of the lambda expression. For one statement body, curly braces are optional, also return statement is optional.
3. The type of the arguments is optional to mention, if not mentioned compiler will identify it.
4. Lambda expression can also be used with “Functional Interface” , i.e. interface with only one method declaration.

Using Lambda expression to our above example :

In our above example, we can convert our Anonymous class to lambda expression as “ICarChecker” is a functional interface.Our Main.java will look like :

public class Main {

    public static void main(String[] args){
        Car audi = new Car("white");
        Car bmw = new Car("black");

        ICarChecker adapter = (Car car) -> {return car.getColor().equalsIgnoreCase("white");};

        System.out.println("Color of Audi checker result : "+adapter.isValidColor(audi));
        System.out.println("Color of bmw checker result : "+adapter.isValidColor(bmw));

    }
}

Instead of creating a new Adapter class and implement the interface, we have done these using only one line.
Since we have only one argument and one expression in the body with a return statement. So, as mentioned above, this lambda expression can be simplified as below :

ICarChecker adapter = car -> car.getColor().equalsIgnoreCase("white");

All these three examples will produce the same output .

Using Lambda expression with Thread and Comparator :

In this example, we will use lambda expression for Runnable to create a thread and inside this thread we will use lambda expression again with Comparator to sort one arraylist using Collections.sort method.
We are using the same example as above . Change Main.java as below :

import java.util.ArrayList;
import java.util.Collections;

public class Main {

    public static void main(String[] args){
        
        //1
        
        Car audi = new Car("white");
        Car bmw = new Car("black");
        Car bentley = new Car("red");
        Car bugatti = new Car("blue");
        Car jaguar = new Car("green");
        
        //2
        ArrayList carList = new ArrayList<>();
        carList.add(audi);
        carList.add(bmw);
        carList.add(bentley);
        carList.add(bugatti);
        carList.add(jaguar);

        System.out.println("Before sorting ...");
        for (Car c : carList){
            System.out.println("Car colour : "+c.getColor());
        }
        
        //3
        Thread sortingThread = new Thread(()->{
            Collections.sort(carList,(car1,car2) -> car1.getColor().compareTo(car2.getColor()));
            
            System.out.println("After sorting...");
            for (Car c : carList){
                System.out.println("Car colour : "+c.getColor());
            }
        });
        sortingThread.start();

    }
}

Explainations :

1. Create 5 “Car” models with different colors. We are going to sort these models on ascending order as its color name.
2. Add all these models in a arraylist “carList
3. Since Runnable is a functional interface, we can use Lambda expression here . Instead of writing :

 Runnable runnable=new Runnable(){  
            public void run(){  
               //sorting code
            }  
        };
        

I have wrote :

()->{ }

And inside the curly braces sorting is done.
Similarly , the method ‘compare‘ of ‘Comparator‘ takes two arguments, we are using (car1,car2) -> {} to replace it. This program will look like below without using lambda expression :

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main {

    public static void main(String[] args){
        Car audi = new Car("white");
        Car bmw = new Car("black");
        Car bentley = new Car("red");
        Car bugatti = new Car("blue");
        Car jaguar = new Car("green");

        ArrayList carList = new ArrayList<>();
        carList.add(audi);
        carList.add(bmw);
        carList.add(bentley);
        carList.add(bugatti);
        carList.add(jaguar);

        System.out.println("Before sorting ...");
        for (Car c : carList){
            System.out.println("Car colour : "+c.getColor());
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Comparator comparator = new Comparator() {
                    @Override
                    public int compare(Car car1, Car car2) {
                        return car1.getColor().compareTo(car2.getColor());
                    }
                };

                Collections.sort(carList,comparator);

                System.out.println("After sorting...");
                for (Car c : carList){
                    System.out.println("Car colour : "+c.getColor());
                }
            }
        };

        Thread sortingThread = new Thread(runnable);
        sortingThread.start();

    }
}