Categories
python

for loop in python

In this tutorial, we will learn about for loop in python. We can iterate an array using for loop.

Syntax

for seq_val in sequence:
  body

Iterate array

cars = ["Honda", "Toyota", "Hyundai"]
for car in cars:
    print(car)

Output

Honda
Toyota
Hyundai

for loop using range

cars = ["Honda", "Toyota", "Hyundai"]
for i in range(len(cars)):
    print(cars[i])
Honda
Toyota
Hyundai

for loop with custom start value

cars = ["Honda", "Toyota", "Hyundai"]
for i in range(2, len(cars)):
    print(cars[i])

Output

Hyundai

Related Articles

Categories
data structures java selection sort

selection sort

In this post, We will learn about the selection sort algorithm in the java language. It is a comparison-based sorting algorithm

Selection sort will select the element from an array, and keep on compare with the remaining elements.

End of each iteration we will obtain the minimum value, After that we will swap the minimum element to the sorted array

Likewise, it will select all the elements in the array and compare them with the remaining element

Unsorted Input array: [ 12, 4, 6, 7, 2, 5 ]
Sorted Output array:  [ 2, 4, 5, 6, 7, 12 ]

Execution Steps

  1. [2, 4, 6, 7, 12, 5]
  2. [2, 4, 6, 7, 12, 5]
  3. [2, 4, 5, 7, 12, 6]
  4. [2, 4, 5, 6, 12, 7]
  5. [2, 4, 5, 6, 7, 12]

Selection Sort

Time Complexity : O(n^2)

Code

package example;

import java.util.Arrays;

public class SelectionSort {

	private void sortArray(int[] arr) {

		for (int i = 0; i < arr.length; i++) {
			int selectionItem = i;
			for (int j = i + 1; j < arr.length; j++) {
				if (arr[j] < arr[selectionItem]) {
					selectionItem = j;
				}
			}
			int temp = arr[selectionItem];
			arr[selectionItem] = arr[i];
			arr[i] = temp;
		}
	}

	public static void main(String[] args) {
		int[] arr = { 12, 4, 6, 7, 2, 5 };
		SelectionSort selectionSort = new SelectionSort();
		selectionSort.sortArray(arr);
		System.out.println(Arrays.toString(arr));
	}
}

Output

[2, 4, 5, 6, 7, 12]

Related Articles

Categories
scala

How to get previous dates using scala

In this post, we will see how to get previous dates using scala.

Scala program – method 1

ZonedDateTime and ZoneId – to get the date and time based on the specific zone id which we prefers to 

DateTimeFormatter – to convert the date and time to a specific format

minusDays function helps us to get the previous dates using scala as below.

import java.time.{ZonedDateTime, ZoneId}
import java.time.format.DateTimeFormatter

object PreviousDate {
  def main(arr: Array[String]): Unit = {
    val previousday = ZonedDateTime.now(ZoneId.of("UTC")).minusDays(1)
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm'Z'")
    val result = formatter format previousday
    println(result)
  }
}
2021-10-01T05:21Z

Scala program – method 2

object YesterdayDate {
  def main(arr: Array[String]): Unit = {
    val today = java.time.LocalDate.now
    val yesterday_date= java.time.LocalDate.now.minusDays(1)
    println(today)
    println(yesterday_date)

  }
}
2021-10-02
2021-10-01

Scala program – method 3

import java.util._
import java.lang._
import java.io._
import java.time.Instant
import java.time.temporal.ChronoUnit


object YesterdayDate {
  def main(arr: Array[String]): Unit = {
    val now = Instant.now
    val yesterday = now.minus(1, ChronoUnit.DAYS)
    System.out.println(now)
    System.out.println(yesterday)
  }
}
2021-10-02T06:37:11.695Z
2021-10-01T06:37:11.695Z

https://github.com/ushanan/SparkFirstProject/blob/master/src/main/scala/com/firstscala/spark/YesterdayDate.scala

Categories
Bubble sort data structures java

bubble sort algorithm

In this post, we will learn about the bubble sort algorithm. The bubble sort algorithm is one of the important sorting algorithms

It will compare two adjacent elements in an array and swap the right value to the left if it is lesser than left

Bubble Sort

Time Complexity: O(n^2)
Values1012462
Position01234
Input Array
Step 1
Iterate the given array using for loop
Step 2 
Add one more iteration within the for loop again
Step 3
compare the first element with second element
Step 4 
If first element greater than second element swap the two elements
Step 5 
Compare the second element with third element 
Step 6
If Second element is greater than third element, then swap the two elements 
Step 7 
Continue until nth element 
Step 1
Step2
Step 3
Step 4
Result of the first iteration

Java Implementation


public class BubbleSort {

	private void sortArray(int arr[]) {
		for (int i = 0; i < arr.length; i++) {
			boolean isSwap = false;
			for (int j = 0; j < arr.length - i - 1; j++) {
				if (arr[j] > arr[j + 1]) {
					int temp = arr[j + 1];
					arr[j + 1] = arr[j];
					arr[j] = temp;
					isSwap = true;
				}
			}
			if (!isSwap) {
				break;
			}
		}
	}

	public static void main(String[] args) {
		int arr[] = { 10, 12, 4, 6, 2 };
		System.out.println("Array Before sorting");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "  ");
		}
		BubbleSort bubbleSort = new BubbleSort();
		bubbleSort.sortArray(arr);

		System.out.println("\nArray After Sorting");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "  ");
		}

	}

}

Output

Array Before sorting
10  12  4  6  2  
Array After Sorting
2  4  6  10  12  
Categories
binary search data structures java

search in rotated sorted array

In this post we will discuss about search in rotated sorted array in efficient way using java

Problem Statement

Input: rotated sorted array
Time Complexity: O(logn)
Efficient Approach: Binary Search

Test Case 1
Input: { 7, 8, 0, 1, 2, 3, 4, 5, 6 }
Target:  8
Output: 1

Test Case 2
Input: { 7, 8, 0, 1, 2, 3, 4, 5, 6 }
Target:  100
Output: -1

Explanation

  • Consider that array doesn’t have duplicates
  • As initial step, we are going to let left pointer =0 & right pointer = array.lenght-1
  • As per binary search we are going to find the mid of the array
  • In case target value matches mid value, then return the mid
  • find the left and right position based on the below solution in iterative way

Solution


public class RotatedBinarySearchExample {

	private int rotatedBinarySearch(int[] nums, int target) {

		// Basic check 
		if (null == nums || nums.length == 0) {
			return -1;
		}
		if (nums.length == 1 && nums[0] == target) {
			return 0;
		}

		int mid = 0;
		int leftPointer = 0;
		int rightPointer = nums.length - 1;

		while (leftPointer <= rightPointer) {

			mid = (leftPointer + rightPointer) / 2;

			if (nums[mid] == target) {
				return mid;
			} else if (nums[leftPointer] <= nums[mid]) { 
				if (target >= nums[leftPointer] && target <= nums[mid]) {
					rightPointer = mid - 1;
				} else {
					leftPointer = mid + 1;
				}

			} else {
				if (target >= nums[mid] && target <= nums[rightPointer]) {
					leftPointer = mid + 1;
				} else {
					rightPointer = mid - 1;
				}
			}
		}
		return -1;
	}

	public static void main(String[] args) {
		RotatedBinarySearchExample rotatedBinarySearchExample = new RotatedBinarySearchExample();
		int[] array = { 7, 8, 0, 1, 2, 3, 4, 5, 6 };
		int targetNumber = 8;
		int output = rotatedBinarySearchExample.rotatedBinarySearch(array, targetNumber);
		System.out.println(output);
	}

}

Output

1

Reference

Categories
binary search data structures java

binary search algorithm

Binary search algorithm is one of the fastest way to identify the element from an sorted array. It is also the commonly asked data structure interview questions.

It works based on divide and conquer mechanism. It will divide the given array into 2 parts and discard the one part. So it will works faster for a big array compared to linear search.

Time complexity of Binary Search is O(logn)

Below is the give array structure

With the above given array we have to find the position of 9, Using linear search we can find easily, But the time complexity will be O(N)

Below is java code snippet to find the position using Binary Search

public class BinarySearchExample {

	private int binarySearch(int[] array, int target) {
		int leftIndex = 0;
		int rightIndex = array.length - 1;
		while (leftIndex <= rightIndex) {
			// find the middle Index
			int middleIndex = (leftIndex + rightIndex) / 2;
			if (array[middleIndex] == target) {
				return middleIndex;
			}
			if (target > array[middleIndex]) {
				// ignoring the left side of array
				leftIndex = middleIndex + 1;
			} else {
				// ignoring the right side of array
				rightIndex = middleIndex - 1;
			}
		}
		return -1;
	}

	public static void main(String[] args) {
		int[] i = { 2, 3, 5, 6, 7, 9,10 };
		int targetNumber = 9;
		BinarySearchExample object = new BinarySearchExample();
		int output = object.binarySearch(i, targetNumber);
		System.out.println(output);
	}

}
Output
5

Categories
python

bar plot in python with example

In this post , let us learn about bar plot in python with example.

Bar plot in python

This helps us to represent the categorical data using rectangular bar with x and y axis.

Codelines

Below are the libraries need to be imported for achieving the graph plotting .

import pandas as pd
from matplotlib import pyplot as plt
a=pd.read_csv('D:\data\shows.csv')
a.head()
Result

The sample file containing nationality details looks like the below.

Age	Experience	Rank	Nationality	Go
0	36	10	9	UK	NO
1	42	12	4	USA	NO
2	23	4	6	N	NO
3	52	4	4	USA	NO
4	43	21	8	USA	YES
Codeline

Country level count can be listed with below syntax.

a['Nationality'].value_counts()
Result
UK     5
N      4
USA    4
Name: Nationality, dtype: int64
Codeline

We can try to get only the country names using keys function.

a['Nationality'].value_counts().keys()
Result
Index(['UK', 'N', 'USA'], dtype='object')
Codeline

The list function groups the various country names.

a['Nationality'].value_counts().keys().tolist()
Result
['UK', 'N', 'USA']
Codeline

The label option will label the x and y axis accordingly.

plt.bar(a['Nationality'].value_counts().keys().tolist(),a['Nationality'].value_counts().tolist())
plt.xlabel("country name")
plt.ylabel("Rank")
plt.title("Nationality detail")
Result
Reference
Categories
Angular

lazy loading in angular

lazy loading in angular is one of the most important concept. You have to understand this while designing an enterprise level angular app

What is lazy loading ?

In single page application we will load all the components and required java script and css files in single shot

But this will take more time when we have more components and more dependencies.

In order to avoid this angular has cool feature which is called lazy loading. which will load required module on need basis

ngModule

ngModule will allow us to group the things together, Module is great way to organize an application

Every angular application will have one base module which is called appModule

@NgModule decorator will make class as module. which will come with declarations,providers,imports. Below is the sample module 

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { LazyRoutingModule } from './lazy-routing.module';
import { LazyComponent } from 'src/app/lazy/lazy/lazy.component';
import { MaterialModule } from '../material/material.module';
import { MatTabsModule } from '@angular/material/tabs';
import {MatCardModule} from '@angular/material/card';
import { SampleComponent } from 'src/app/lazy/sample/sample/sample.component';
import {MatButtonModule} from '@angular/material/button';


@NgModule({
  declarations: [LazyComponent,SampleComponent],
  imports: [
    CommonModule,
    LazyRoutingModule,
    MaterialModule,
  ]
})
export class LazyModule { }

Lazy Loading Steps

  • Create new angular project
    • ng new lazy-example –routing
  • Create new component(HomeComponent)
    • ng new component home
  • Create new Component (LazyComponent)
    • ng new component lazy
  • Create new module(LazyModule)
    • ng new module lazy –routing

Below is the folder structure of our application

We have two components.& two Modules

  • AppModule is the base module used while application launch
  • LazyModule is the lazy module used while user clicks the lazy url
  • HomeComponent will get initialized while application launch via appModule
  • LazyComponent will get initialized while clicking the lazy routing url via LazyModule

Declare the HomeComponent in AppModule as like below

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { HomeComponent } from './components/home/home.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  declarations: [AppComponent, HomeComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

Declare the LazyComponent in LazyModule as like below

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LazyRoutingModule } from './lazy-routing.module';
import { MatTabsModule } from '@angular/material/tabs';
import { LazyComponent } from '../../components/lazy/lazy.component';

@NgModule({
  imports: [CommonModule, LazyRoutingModule, MatTabsModule],
  declarations: [LazyComponent]
})
export class LazyModule {}

The important point is routing. We have to mention that load children (LazyModule) in app-routing.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { LazyModule } from './modules/lazy/lazy.module';
import { HomeComponent } from './components/home/home.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'lazy', loadChildren: () => LazyModule }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule {}

As like app-routing we have to mention the home path in lazy-routing.module.ts file as like below

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LazyComponent } from '../../components/lazy/lazy.component';

const routes: Routes = [{ path: '', component: LazyComponent }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  declarations: []
})
export class LazyRoutingModule {}

That’s it you can see the output as like below

StackBlitz URL:

https://stackblitz.com/edit/angular-ivy-rpqusl?file=src/app/app.component.ts

Related Articles

Categories
SQL

Referential integrity in SQL

In this post , Let us learn Referential integrity in SQL .

What is Referential integrity ?

Referential integrity in SQL requires that a foreign key must have a matching primary key or it must be null. This constraint is specified between parent and child table.It actually maintains the correspondence between rows in these tables.

What is Primary key ?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

program

CREATE TABLE Emp_detail (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (ID)
);

What is Foreign key?

Foreign key is used to maintain relationship between two tables. Primary of a table act as foreign key in the other table.

program

CREATE TABLE Emp_salary (
	Dep_id int,
    ID int NOT NULL,
	Salary int,
    PRIMARY KEY (Dep_id),
    FOREIGN KEY (ID) REFERENCES Emp_detail(ID)
);

In this way, the referential integrity makes parent table getting co-related with child table .

Rules of Referential integrity

We cant add a record to the table that contains the foreign key unless there is a corresponding record in the linked table.

cascading update and cascading delete are the other new techniques . This ensures that changes made to the linked table gets reflected in the primary table.

Benefits of Referential Integrity

  • Restricts the entry of duplicate data
  • Avoids one table from pointing to a nonexistent field in another table
  • Prevents the deletion of a record that contains a value referred to by a foreign key in another table
  • Prevents for the addition of a record to a table that contains a foreign key unless there is a primary key in the linked table

Reference

https://towardsdatascience.com/common-issues-founded-with-referential-integrity-fc05e93693a1

Categories
ansible devops

ansible playbook example

In this post we will see ansible playbook example, Play book is written in yaml format. Inside that we will have multiple tasks and roles

Below is the simple ansible play book with mutiple task

---
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"	
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"

Related Articles

when condition in ansible playbook