type casting int : <class 'int'>
type casting float : <class 'float'>
type casting string : <class 'str'>
type casting boolean : <class 'bool'>
type casting list : <class 'list'>
type casting set : <class 'set'>
type casting tuple : <class 'tuple'>
Delete Variable
Delete an existing variable using Pythonβs del keyword.
temp = 1
print("temp variable is : ",temp)
del temp
# print(temp) => throw NameError : temp not defined
Output
temp variable is : 1
Find Variable Memory Address
Use the id() function to find the memory address of a variable.
temp = "hi"
print("address of temp variable : ",id(temp))
Output
address of temp variable : 140710894284672
Constants
Python does not have a direct keyword for constants, but namedtuple can be used to create constants.
from collections import namedtuple
const = namedtuple("const",["PI"])
math = const(3.14)
print("namedtuple PI = ",math.PI)
print("namedtuple type =",type(math))
Output
namedtuple PI = 3.14
namedtuple type = <class '__main__.const'>
Global Keyword
Before understanding global keyword, understand function-scoped variables.
Function inside variable are stored in stack memory.
A function cannot modify an outside (global) variable directly, but it can access it.
To create a reference to a global variable inside a function, use the global keyword.
// 1. Reverse an ArrayList without using inbuilt method
// 2. Find Duplicate Elements in a List
// 3. Alphabetical Order and Ascending Order (Done in ArrayList)
// 4. Merge Two Lists and Remove Duplicates
// 5. Removing Even Nos from the List
// 6. Array to List, List to Array
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
public class CollectionsInJava {
public static void main(String[] args) {
// 1. Reverse an ArrayList without using inbuilt method
// 2. Find Duplicate Elements in a List
// 3. Alphabetical Order and Ascending Order (Done in ArrayList)
// 4. Merge Two Lists and Remove Duplicates
// 5. Removing Even Nos from the List
// 6. Array to List, List to Array
ArrayList<String> names = new ArrayList<>(Arrays.asList("Abinaya", "Ramya", "Gowri", "Swetha", "Sugi", "Anusuya", "Moogambigai","Jasima","Aysha"));
ArrayList<Integer> al2 = new ArrayList<>(Arrays.asList(100,90,30,20,60,40));
ArrayList<Integer> al = insertValuesIntoAL();
System.out.println("Before Reversing ArrayList="+ al);
System.out.println("Reversed ArrayList="+ reverseArrayList(al));
System.out.println("Duplicates in ArrayList="+findDuplicates(al));
System.out.println("Before Order = "+names);
Collections.sort(names);
System.out.println("After Alphabetical Order = " + names);
Collections.sort(al);
System.out.println("Ascending Order = "+ al);
System.out.println("List -1 = "+al);
System.out.println("List -2 = "+al2);
System.out.println("After Merging and Removing Duplicates="+mergeTwoLists(al,al2));
System.out.println("After Removing Even Nos fromt the List-1 = "+removeEvenNos(al));
arrayToListViceVersa(al,new int[] {11,12,13,14,15}); //Sending ArrayList and anonymous array
}
// 1. Reverse an ArrayList without using inbuilt method
private static ArrayList<Integer> reverseArrayList(ArrayList<Integer> al) {
int n=al.size();
int j=n-1, mid=n/2;
for (int i=0; i<mid; i++) {
int temp = al.get(i);
al.set(i, al.get(j));
al.set(j--, temp);
}
return al;
}
// 2. Find Duplicate Elements in a List
private static ArrayList<Integer> findDuplicates(ArrayList<Integer> al) {
HashSet<Integer> hs = new HashSet<>();
ArrayList<Integer> arl = new ArrayList<>();
for (int ele:al) {
if (!hs.add(ele)) arl.add(ele);
}
return arl;
}
//4. Merge Two Lists into one and Remove Duplicates
private static HashSet<Integer> mergeTwoLists(ArrayList<Integer> arl1,ArrayList<Integer> arl2) {
ArrayList<Integer> resAl = new ArrayList<>();
HashSet<Integer> hs = new HashSet<>();
hs.addAll(arl1);
hs.addAll(arl2);
return hs;
}
// 5. Removing Even Nos from the List
private static ArrayList<Integer> removeEvenNos(ArrayList<Integer> al) {
ArrayList<Integer> res = new ArrayList<>();
Iterator itr = al.iterator();
while (itr.hasNext()) {
int ele = (int)itr.next();
if (ele%2==1) res.add(ele);
}
return res;
}
// 6. Array to List, List to Array
private static void arrayToListViceVersa(ArrayList<Integer> arl, int[] ar) {
Integer arr[] = arl.toArray(new Integer[0]);
System.out.println("Convert List to Array = " + Arrays.toString(arr));
List<Integer> lst = Arrays.asList(arr);
System.out.println("Convert Array to List = " + lst);
}
private static ArrayList<Integer> insertValuesIntoAL() {
Integer[] ar = {30,40,60,10,94,23,05,46, 40, 94};
ArrayList<Integer> arl = new ArrayList<>();
Collections.addAll(arl, ar);
//Collections.reverse(al); //IN BUILT METHOD
return arl;
//Arrays.sort(ar);
//List lst = Arrays.asList(ar); //TBD
//return new ArrayList<Integer>(lst);
}
}
package taskPkg;
import java.util.Scanner;
public class SubArray {
public static void main(String[] args) {
// FINDING SUBARRAY AND ITS POSITION
System.out.println("Enter a sentence to search in.");
Scanner scn = new Scanner(System.in);
String sentn = scn.nextLine();
System.out.println("Enter a word to be searched.");
String word = scn.next();
scn.close();
char[] sentence = sentn.toCharArray();
char[] key = word.toCharArray();
int n = sentence.length, m = key.length;
int i = 0, j = 0, st = 0; // i- maintain index in the sentence, j-maintain index in key
boolean match = false;
while (i < n && j < m) {//
//System.out.println("i=" + i + " sentence[i]=" + sentence[i] + " j=" + j + " key[j]=" + key[j]);
if (sentence[i] == key[j]) { //if it matches incrementing both pos
i++;
j++;
if (j == m) { //if the key reaches end, made the match and exit
match = true;
break;
}
}
else { // if no match move on to the next letter, but key should start from 0
j = 0;
i=st+1;
st = i; // this is to save the starting of the subarray
}
}
if (match)
System.out.println("SubArray is found at " + st);
else
System.out.println("SubArray is not found");
}
}
First Letter Occurrence, Last Letter Occurrence in the given Word
Print Reversed Array
Cricketers array and their best score array β Give name as input and get the high score.
package taskPkg;
import java.util.Scanner;
public class ArraysBasics {
//1. PRINTING 1ST LETTER OF THE CHAR ARRAY
//2. PRINT REVERSED A CHAR ARRAY
//3.
public static void main(String[] args) {
// TODO Auto-generated method stub
ArraysBasics obj = new ArraysBasics();
Scanner scn = new Scanner(System.in);
System.out.println("Enter a name to find its first and Last Letter.");
String nam = scn.next();
char[] name = nam.toCharArray();
System.out.println("First Letter of "+nam+" is repeated at "+obj.findFirstLtr(name));
System.out.println("Last Letter of "+nam+" is repeated at "+obj.findLastLtr(name));
obj.printReversedArray(name);
System.out.println();
String[] cricketers = {"Rohit","Suryakumar","Ashwin", "Jadeja","Yashasvi"};
int[] scores = {100,120,86,102,98};
System.out.println("Enter one cricketer name to get his high score");
String givenName = scn.next();
System.out.println("Score for " + givenName+ " is "+obj.getScore(cricketers,scores,givenName));
}
private int findFirstLtr(char name[]) {
char ch = name[0];
for (int i=1; i<name.length; i++) {
if (ch==name[i]) return i;
}
return -1;
}
private int findLastLtr(char name[]) {
char ch = name[name.length-1];
for (int i=0; i<name.length-1; i++) {
if (ch==name[i]) return i;
}
return -1;
}
private void printReversedArray(char[] name) {
System.out.println("Reversed Array = ");
for (int i=name.length-1; i>=0; i--) {
System.out.println(" "+name[i]);
}
}
private int getScore(String[] name, int[] score, String givenName) {
int n = name.length;
for(int i=0; i<n; i++) {
if(name[i].equals(givenName)) return score[i];
}
return 0;
}
}