3.
STRING VALIDATION
function validateString(input) {
// Define a regular expression pattern
const pattern = /^[a-zA-Z0-9]+$/; // Only allows alphanumeric characters
// Test the input string against the pattern
if (pattern.test(input)) {
console.log("Valid string");
} else {
console.log("Invalid string");
// Example usage
validateString("Hello123"); // Output: Valid string
validateString("Hello 123!"); // Output: Invalid string
NUMBER OPERATORS
class NumberOperations:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
# Method to add two numbers
def add(self):
return self.num1 + self.num2
# Method to subtract two numbers
def subtract(self):
return self.num1 - self.num2
# Method to multiply two numbers
def multiply(self):
return self.num1 * self.num2
# Method to divide two numbers
def divide(self):
if self.num2 != 0:
return self.num1 / self.num2
else:
return 'Division by zero is not allowed'
# Create an object of the NumberOperations class
operations = NumberOperations(10, 5)
print('Addition:', operations.add()) # Output: 15
print('Subtraction:', operations.subtract()) # Output: 5
print('Multiplication:', operations.multiply()) # Output: 50
print('Division:', operations.divide()) # Output: 2
STRING VALIDATION II
class StringValidator {
constructor() {}
// Method to check if the string is not empty
isNotEmpty(str) {
return str.trim().length > 0;
// Method to check if the string contains only letters
isAlpha(str) {
return /^[a-zA-Z]+$/.test(str);
// Method to check if the string is a valid email
isEmail(str) {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(str);
// Method to check if the string length is within a specified range
isLengthInRange(str, min, max) {
return str.length >= min && str.length <= max;
// Example usage:
const validator = new StringValidator();
const testString = "hello@example.com";
console.log(validator.isNotEmpty(testString)); // true
console.log(validator.isAlpha(testString)); // false
console.log(validator.isEmail(testString)); // true
console.log(validator.isLengthInRange(testString, 5, 20)); // true
DUPLICATE NUMBER
def find_duplicates(arr):
# Dictionary to store the count of each number
count = {}
# List to store the duplicates
duplicates = []
# Iterate through the array
for num in arr:
# If the number is already in the dictionary, increment its count
if num in count:
count[num] += 1
else:
# Otherwise, set its count to 1
count[num] = 1
# Iterate through the dictionary to find duplicates
for key, value in count.items():
if value > 1:
duplicates.append(key)
return duplicates
# Example usage
numbers = [1, 2, 3, 4, 5, 2, 3, 6, 7, 8, 3]
duplicates = find_duplicates(numbers)
print(duplicates) # Output: [2, 3]
INTERSECTION OF TWO ARRAYS
def intersection(arr1, arr2):
# Convert the second array to a set for efficient look-up
set_b = set(arr2)
# Filter the first array to include only elements that are in the set
intersection_result = [num for num in arr1 if num in set_b]
return intersection_result
# Example usage
array1 = [1, 2, 3, 4, 5]
array2 = [3, 4, 5, 6, 7]
result = intersection(array1, array2)
print(result) # Output: [3, 4, 5]
FIRST UNIQUE CHARACTER
def first_unique_character(s):
# Dictionary to store the frequency of each character
char_count = {}
# Iterate through the string to populate the frequency dictionary
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# Iterate through the string again to find the first unique character
for char in s:
if char_count[char] == 1:
return char
# If no unique character is found, return None
return None
# Example usage
input_string = "swiss"
unique_char = first_unique_character(input_string)
print(unique_char) # Output: "w"
REVERSE VOWELS
class VowelReverser:
def __init__(self):
self.vowels = 'aeiouAEIOU'
def is_vowel(self, char):
return char in self.vowels
def reverse_vowels(self, s):
chars = list(s)
left, right = 0, len(chars) - 1
while left < right:
if not self.is_vowel(chars[left]):
left += 1
continue
if not self.is_vowel(chars[right]):
right -= 1
continue
# Swap the vowels
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
return ''.join(chars)
# Example usage
reverser = VowelReverser()
input_string = "hello world"
result = reverser.reverse_vowels(input_string)
print(result) # Output: "hollo werld"
TWIN PRIME
class PrimeUtils:
# Method to check if a number is prime
def is_prime(self, num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i=5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
# Method to find twin primes up to a given limit
def find_twin_primes(self, limit):
twin_primes = []
for i in range(2, limit - 1):
if self.is_prime(i) and self.is_prime(i + 2):
twin_primes.append((i, i + 2))
return twin_primes
# Example usage
prime_utils = PrimeUtils()
limit = 100
twin_primes = prime_utils.find_twin_primes(limit)
print(twin_primes) # Output: [(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), (59, 61), (71, 73)]
ELECTRICITY BILL
class ElectricityBill:
def __init__(self, units):
self.units = units
def calculate_bill(self):
bill = 0
if self.units <= 100:
bill = self.units * 10
elif self.units <= 200:
bill = (100 * 10) + ((self.units - 100) * 15)
elif self.units <= 300:
bill = (100 * 10) + (100 * 15) + ((self.units - 200) * 20)
else:
bill = (100 * 10) + (100 * 15) + (100 * 20) + ((self.units - 300) * 25)
return bill
# Example usage
units_consumed = 250
bill_calculator = ElectricityBill(units_consumed)
total_bill = bill_calculator.calculate_bill()
print(f"Total Electricity Bill: ₹{total_bill}") # Output: Total Electricity Bill: ₹3500
DISCOUNTED PRICE
class DiscountCalculator:
def __init__(self, original_price, discount_rate):
self.original_price = original_price
self.discount_rate = discount_rate
def calculate_discounted_price(self):
discount = self.original_price * (self.discount_rate / 100)
discounted_price = self.original_price - discount
return f"{discounted_price:.2f}"
# Example usage
original_price = 1000 # Original price in currency units
discount_rate = 20 # Discount rate in percentage
calculator = DiscountCalculator(original_price, discount_rate)
discounted_price = calculator.calculate_discounted_price()
print(f"Discounted Price: ₹{discounted_price}") # Output: Discounted Price: ₹800.00
NEW PASSWORD GENERATION
import random
class PasswordGenerator:
def __init__(self, length):
self.length = length
self.characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%&*'
def generate_password(self):
password = ''.join(random.choice(self.characters) for _ in range(self.length))
return password
# Example usage
password_length = 12 # Desired password length
generator = PasswordGenerator(password_length)
new_password = generator.generate_password()
print(f"Generated Password: {new_password}") # Output: Generated Password: a1B2c3D4e5F6
STUDENT ATTENDANCE RECORD
class Student:
def __init__(self, student_id, name):
self.id = student_id
self.name = name
self.attendance = []
def mark_attendance(self, date, status):
self.attendance.append({'date': date, 'status': status})
def get_attendance(self):
return self.attendance
class AttendanceSystem:
def __init__(self):
self.students = {}
def add_student(self, student_id, name):
if student_id not in self.students:
self.students[student_id] = Student(student_id, name)
else:
print(f"Student with ID {student_id} already exists.")
def mark_attendance(self, student_id, date, status):
if student_id in self.students:
self.students[student_id].mark_attendance(date, status)
else:
print(f"Student with ID {student_id} not found.")
def get_student_attendance(self, student_id):
if student_id in self.students:
return self.students[student_id].get_attendance()
else:
print(f"Student with ID {student_id} not found.")
return []
# Example usage
attendance_system = AttendanceSystem()
attendance_system.add_student(1, 'John Doe')
attendance_system.add_student(2, 'Jane Smith')
attendance_system.mark_attendance(1, '2024-10-03', 'Present')
attendance_system.mark_attendance(2, '2024-10-03', 'Absent')
print(attendance_system.get_student_attendance(1)) # Output: [{'date': '2024-10-03', 'status':
'Present'}]
print(attendance_system.get_student_attendance(2)) # Output: [{'date': '2024-10-03', 'status':
'Absent'}]