slips
November 30, 2023
SLIP18
Q.1 Write a Java Program to implement Abstract Factory Pattern for Bank and Loan.
import java.util.Scanner;
// Abstract Bank class
interface Bank {
String getBankName();
}
// Concrete Bank classes
class SBI implements Bank {
@Override
public String getBankName() {
return "SBI Bank";
}
}
class ICICI implements Bank {
@Override
public String getBankName() {
return "ICICI Bank";
}
}
class Kotak implements Bank {
@Override
public String getBankName() {
return "KOTAK Bank";
}
}
// Abstract Loan class
abstract class Loan {
abstract String getLoanType();
abstract double calculateEMI(double loanAmount, double interestRate, int yearsToRepay);
}
// Concrete Loan classes
class HomeLoan extends Loan {
@Override
String getLoanType() {
return "Home Loan";
}
@Override
double calculateEMI(double loanAmount, double interestRate, int yearsToRepay) {
// Formula for EMI calculation: EMI = [P * r * (1 + r)^n] / [(1 + r)^n - 1]
double r = interestRate / 1200; // Monthly interest rate
int n = yearsToRepay * 12; // Total number of payments
double emi = (loanAmount * r * Math.pow(1 + r, n)) / (Math.pow(1 + r, n) - 1);
return emi;
}
}
class EducationLoan extends Loan {
@Override
String getLoanType() {
return "Education Loan";
}
@Override
double calculateEMI(double loanAmount, double interestRate, int yearsToRepay) {
// Formula for EMI calculation: EMI = [P * r * (1 + r)^n] / [(1 + r)^n - 1]
double r = interestRate / 1200; // Monthly interest rate
int n = yearsToRepay * 12; // Total number of payments
double emi = (loanAmount * r * Math.pow(1 + r, n)) / (Math.pow(1 + r, n) - 1);
return emi;
}
}
// Abstract Factory interface
interface AbstractLoanFactory {
Bank createBank();
Loan createLoan();
}
// Concrete Factory for Home Loan
class HomeLoanFactory implements AbstractLoanFactory {
@Override
public Bank createBank() {
return new SBI(); // Can be replaced with ICICI or Kotak as needed
}
@Override
public Loan createLoan() {
return new HomeLoan();
}
}
// Concrete Factory for Education Loan
class EducationLoanFactory implements AbstractLoanFactory {
@Override
public Bank createBank() {
return new ICICI(); // Can be replaced with SBI or Kotak as needed
}
@Override
public Loan createLoan() {
return new EducationLoan();
}
}
// Client code
public class AbstractFactoryPatternExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Accept user input for loan type
System.out.println("Select loan type: ");
System.out.println("1. Home Loan");
System.out.println("2. Education Loan");
int loanTypeChoice = scanner.nextInt();
AbstractLoanFactory loanFactory;
if (loanTypeChoice == 1) {
loanFactory = new HomeLoanFactory();
} else if (loanTypeChoice == 2) {
loanFactory = new EducationLoanFactory();
} else {
System.out.println("Invalid choice. Exiting program.");
return;
}
// Create Bank and Loan objects based on user selection
Bank bank = loanFactory.createBank();
// Accept user input for bank type
System.out.println("Select bank type: ");
System.out.println("1. SBI");
System.out.println("2. ICICI");
System.out.println("3. Kotak");
int bankTypeChoice = scanner.nextInt();
switch (bankTypeChoice) {
case 1:
bank = new SBI();
break;
case 2:
bank = new ICICI();
break;
case 3:
bank = new Kotak();
break;
default:
System.out.println("Invalid choice. Using default bank.");
}
Loan loan = loanFactory.createLoan();
// Accept additional input from the user
System.out.print("Enter the loan amount: ");
double loanAmount = scanner.nextDouble();
System.out.print("Enter the interest rate (in percentage): ");
double interestRate = scanner.nextDouble();
System.out.print("Enter the number of years to repay: ");
int yearsToRepay = scanner.nextInt();
// Calculate EMI and display the results
double emi = loan.calculateEMI(loanAmount, interestRate, yearsToRepay);
System.out.println("\nLoan details:");
System.out.println("Bank: " + bank.getBankName());
System.out.println("Loan Type: " + loan.getLoanType());
System.out.println("Loan Amount: quot; + loanAmount);
System.out.println("Interest Rate: " + interestRate + "%");
System.out.println("Number of Years to Repay: " + yearsToRepay);
System.out.println("EMI (Equated Monthly Installment): quot; + emi);
scanner.close();
}
}
Q.2 Write a python program to implement linear SVM for Regression. Use position_sal.csv
import pandas as pd
from sklearn.svm import SVR
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
data = pd.read_csv('./csv//position_sal.csv')
X = data.iloc[:, 1:2].values # Assuming the independent variable is in the second column
y = data.iloc[:, -1].values # Assuming the dependent variable (target) is in the last column
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
sc_X = StandardScaler()
sc_y = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
y_train = sc_y.fit_transform(y_train.reshape(-1, 1)).ravel()
svm_regressor = SVR(kernel='linear')
svm_regressor.fit(X_train, y_train)
y_pred = svm_regressor.predict(X_test)
y_pred = y_pred.reshape(-1, 1) # Reshape predictions to match the expected shape for inverse_transform
y_pred = sc_y.inverse_transform(y_pred) # Inverse transform predictions to original scale
rmse = mean_squared_error(y_test, y_pred, squared=False)
print("Root Mean Squared Error (RMSE):", rmse)
plt.scatter(X_test, y_test, color='blue', label='Actual')
plt.scatter(X_test, y_pred, color='red', label='Predicted')
plt.title('Linear SVM Regression')
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.legend()
plt.show()
Q.3 Implement useEffect hook and print all three life cycle states a. e.g Inside mount b. e.g Inside update c. e.g Inside unmount
Paste LifecycleExample.jsx in src folder
After Running The React App On Port . Press Right Click On Web Page And Choose Inspect Option And Select The Console Tab To Show The Log .
import React, { useState, useEffect } from 'react';
const LifecycleExample = () => {
// Mounting
useEffect(() => {
console.log('Inside mount');
// Cleanup function (will be called on unmount)
return () => {
console.log('Inside unmount');
};
}, []);
// Updating
useEffect(() => {
console.log('Inside update');
// Cleanup function (will be called on update and unmount)
return () => {
console.log('Inside unmount (from update)');
};
});
// State for updating
const [count, setCount] = useState(0);
return (
<div>
<h1>Lifecycle Example</h1>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase Count</button>
</div>
);
};
export default LifecycleExample;