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 ([Link](input)) {
[Link]("Valid string");
} else {
[Link]("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:', [Link]()) # Output: 15
print('Subtraction:', [Link]()) # Output: 5
print('Multiplication:', [Link]()) # Output: 50
print('Division:', [Link]()) # Output: 2
STRING VALIDATION II
class StringValidator {
constructor() {}
// Method to check if the string is not empty
isNotEmpty(str) {
return [Link]().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 [Link](str);
// Method to check if the string length is within a specified range
isLengthInRange(str, min, max) {
return [Link] >= min && [Link] <= max;
// Example usage:
const validator = new StringValidator();
const testString = "hello@[Link]";
[Link]([Link](testString)); // true
[Link]([Link](testString)); // false
[Link]([Link](testString)); // true
[Link]([Link](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 [Link]():
if value > 1:
[Link](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):
[Link] = 'aeiouAEIOU'
def is_vowel(self, char):
return char in [Link]
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):
[Link] = units
def calculate_bill(self):
bill = 0
if [Link] <= 100:
bill = [Link] * 10
elif [Link] <= 200:
bill = (100 * 10) + (([Link] - 100) * 15)
elif [Link] <= 300:
bill = (100 * 10) + (100 * 15) + (([Link] - 200) * 20)
else:
bill = (100 * 10) + (100 * 15) + (100 * 20) + (([Link] - 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):
[Link] = length
[Link] =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%&*'
def generate_password(self):
password = ''.join([Link]([Link]) for _ in range([Link]))
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):
[Link] = student_id
[Link] = name
[Link] = []
def mark_attendance(self, date, status):
[Link]({'date': date, 'status': status})
def get_attendance(self):
return [Link]
class AttendanceSystem:
def __init__(self):
[Link] = {}
def add_student(self, student_id, name):
if student_id not in [Link]:
[Link][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 [Link]:
[Link][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 [Link]:
return [Link][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'}]