0% found this document useful (0 votes)
34 views

NM Python Programs

Uploaded by

23bsds152sanjays
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

NM Python Programs

Uploaded by

23bsds152sanjays
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

1.

ATM SIMULATION WITH WITHDRAWAL LIMITS AND CONDITIONS:

class ATM:
count_per=0
atm_balance = 100000
def __init__(self, balance=0):
self.balance = balance
ATM.count_per += 1
print("ATM created")
def withdraw(self, amount):
if ATM.count_per > 5:
print("Limit exceeded")
return
if amount > self.balance:
print("Insufficient funds")
else:
if amount > self.atm_balance:
print("ATM balance is not sufficient")
else:
if amount % 100 != 0:
print("Amount must be a multiple of 100")
else:
self.balance -= amount
print("Withdrawal successful")
p1=ATM(1000)
p1.withdraw(500)
print(p1.balance)
p2=ATM(2000)
p2.withdraw(1000)
print(p2.balance)

OUTPUT:

ATM created
Withdrawal successful
500
ATM created
Withdrawal successful
1000

2. SEQUENCE REMOVAL:

class seq_rem:
def __init__(self,string,indices):
self.string=string
self.indices=indices
def remove_chars_at_indices(self):
# Convert the string to a list for easier manipulation
char_list = list(self.string)

# Sort the indices in descending order to avoid shifting issues while


removing characters
self.indices = sorted(self.indices, reverse=True)

# Remove characters at each index


for index in self.indices:
if 0 <= index < len(char_list):
char_list.pop(index)

# Join the list back into a string


return ''.join(char_list)

# Example usage
seq_rem = seq_rem("Hello, World!", [0, 2, 4, 7])
result = seq_rem.remove_chars_at_indices()
print("Result:", result)

OUTPUT:

elo,Word!

3. WORD CHECKER:

class WordChecker:
def __init__(self, word):
self.word = word

def check_word(self):
# Check if word length is less than 3
if len(self.word) < 3:
return "Invalid"

second_char = self.word[1]

# Check if second character is a vowel


if second_char.isalpha():
if second_char.lower() in 'aeiou':
return "Vowel"
else:
return "Consonant"
# Check if second character is a digit
elif second_char.isdigit():
return "Digit"
else:
return "Others"

# Example usage
word = input("Enter a word: ")
checker = WordChecker(word)
result = checker.check_word()
print("Result:", result)

OUTPUT:

Enter a word: a124


Result: Digit

4. NUMBER CHECKER:

class NumberChecker:
def __init__(self, X):
self.number = X

def check_number(self):
# Convert the number to a string to check digits
num_str = str(self.number)

# If it's a single digit number, display the square of the number


if len(num_str) == 1:
return f"Square of the number: {self.number ** 2}"

# If the number has more than 1 digit


second_digit = int(num_str[1])

# If the second digit is divisible by both 2 and 4, display "24"


if second_digit % 2 == 0 and second_digit % 4 == 0:
return "24"
# Else if the number is even, display "2"
elif self.number % 2 == 0:
return "2"
# Else if the number is odd, display "1"
else:
return "1"

# Example usage
X = int(input("Enter a number: "))
checker = NumberChecker(X)
result = checker.check_number()
print("Result:", result)

OUTPUT:

Enter a number: 15
Result: 1

5. DUPLICATE CHECKER:

class DuplicateChecker:
def __init__(self, A):
self.array = A

def find_duplicate(self):
num_set = set()

for num in self.array:


# If the number is already in the set, it's the duplicate
if num in num_set:
return num
else:
num_set.add(num)

# If no duplicate is found, return -1


return -1

# Example usage
N = int(input("Enter the number of elements in the array: "))
A = list(map(int, input("Enter the elements of the array: ").split()))

checker = DuplicateChecker(A)
duplicate = checker.find_duplicate()
print("Duplicate number:", duplicate)

OUTPUT:

Enter the number of elements in the array: 5


Enter the elements of the array: 1 3 5 3 1
Duplicate number: 3
6. INTERSECTION:

class ArrayIntersection:
def __init__(self, A, B):
self.array_A = A
self.array_B = B

def find_intersection(self):
# Convert the arrays into sets to efficiently compute intersection
set_A = set(self.array_A)
set_B = set(self.array_B)

# Compute the intersection of both sets


intersection = set_A.intersection(set_B)

# Convert the result back to a sorted list (optional)


return sorted(list(intersection))

# Example usage
A = list(map(int, input("Enter the elements of the first array (space-
separated): ").split()))
B = list(map(int, input("Enter the elements of the second array (space-
separated): ").split()))

checker = ArrayIntersection(A, B)
result = checker.find_intersection()
print("Intersection:", result)

OUTPUT:

Enter the elements of the first array (space-separated): 1 2 3


Enter the elements of the second array (space-separated): 1 3 4
Intersection: [1, 3]

7. FIRST NON REPEATING CHARACTER:

class FirstNonRepeatingCharacter:
def __init__(self, S):
self.string = S

def find_first_non_repeating(self):
# Dictionary to store the frequency of characters
char_count = {}

# First pass: count occurrences of each character


for char in self.string:
char_count[char] = char_count.get(char, 0) + 1
print(char_count)

# Second pass: find the first character with a count of 1


for index, char in enumerate(self.string):
if char_count[char] == 1:
return index

# If no non-repeating character found, return -1


return -1

# Example usage
S = input("Enter a string: ")
checker = FirstNonRepeatingCharacter(S)
result = checker.find_first_non_repeating()
print("Index of the first non-repeating character:", result)

OUTPUT:

Enter a string: sasatha


{'s': 1}
{'s': 1, 'a': 1}
{'s': 2, 'a': 1}
{'s': 2, 'a': 2}
{'s': 2, 'a': 2, 't': 1}
{'s': 2, 'a': 2, 't': 1, 'h': 1}
{'s': 2, 'a': 3, 't': 1, 'h': 1}
Index of the first non-repeating character: 4

8. REVERSE VOWELS:

class ReverseVowels:
def __init__(self, string):
self.string = string

def reverse_only_vowels(self):
vowels = 'aeiouAEIOU' # Define the vowels (both lowercase and
uppercase)
# Extract vowels from the string
vowel_list = [char for char in self.string if char in vowels]

# Create a list to hold the result


result = []
vowel_index = len(vowel_list) - 1 # Start from the end of the
vowel list
# Traverse the original string and replace vowels with those from
the vowel list
for char in self.string:
if char in vowels:
result.append(vowel_list[vowel_index]) # Append the last
vowel
vowel_index -= 1 # Move to the previous vowel
else:
result.append(char) # Append consonants as they are

# Join the list into a string and return it


return ''.join(result)

# Example usage
input_string = input("Enter a string: ")
reverser = ReverseVowels(input_string)
output_string = reverser.reverse_only_vowels()
print("String after reversing vowels:", output_string)

OUTPUT:

Enter a string: geetha


String after reversing vowels: gaethe

9. TWIN PRIME:

class TwinPrimeCounter:
def __init__(self, array):
self.array = array

def is_prime(self, num):


""" Check if a number is prime. """
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

def count_twin_primes(self):
""" Count all possible twin prime pairs in the array. """
# Filter the array to get only prime numbers
prime_numbers = [num for num in self.array if self.is_prime(num)]
# Sort the prime numbers for easier twin prime checking
prime_numbers.sort()

twin_prime_count = 0

# Count pairs of twin primes


for i in range(len(prime_numbers) - 1):
if prime_numbers[i + 1] - prime_numbers[i] == 2:
twin_prime_count += 1

return twin_prime_count

# Example usage
N = int(input("Enter the number of elements in the array: "))
A = list(map(int, input("Enter the elements of the array: ").split()))

counter = TwinPrimeCounter(A)
result = counter.count_twin_primes()
print("Number of twin prime pairs:", result)

OUTPUT:

Enter the number of elements in the array: 5


Enter the elements of the array: 1 2 4 5 3
Number of twin prime pairs: 1

10. ELECTRICITY BILL:

class ElectricityBill:
def __init__(self, units):
self.units = units

def calculate_bill(self):
if self.units < 0:
return "Invalid number of units."

bill_amount = 0

# Calculate the bill based on the given unit ranges


if 1 <= self.units <= 25:
bill_amount = self.units * 1.25
elif 26 <= self.units <= 50:
bill_amount = 25 * 1.25 + (self.units - 25) * 1.45
elif 51 <= self.units <= 75:
bill_amount = 25 * 1.25 + 25 * 1.45 + (self.units - 50) * 1.65
elif 76 <= self.units <= 95:
bill_amount = 25 * 1.25 + 25 * 1.45 + 25 * 1.65 + (self.units
- 75) * 1.95
elif self.units > 95:
bill_amount = 25 * 1.25 + 25 * 1.45 + 25 * 1.65 + 20 * 1.95 +
(self.units - 95) * 2.00

return round(bill_amount, 2) # Round the bill amount to 2 decimal


places

# Example usage
try:
U = int(input("Enter the number of metered units: "))
bill_calculator = ElectricityBill(U)
bill_amount = bill_calculator.calculate_bill()
print("Electricity Bill Amount: $", bill_amount)
except ValueError:
print("Please enter a valid number of units.")

OUTPUT:

Enter the number of metered units: 35


Electricity Bill Amount: $ 45.75

11. PURCHASE:

class Purchase:
def __init__(self, N, P):
self.N = N # Number of items
self.P = P # Price per item

def calculate_discounted_items(self):
""" Calculate the number of discounted items based on the number
of items purchased. """
if self.N < 50:
return 0
elif self.N <= 100:
return 10
elif self.N <= 200:
return 20
else:
return 30
def calculate_total_amount(self):
""" Calculate the total amount before any discounts. """
discounted_items = self.calculate_discounted_items()
total_items_billed = max(0, self.N - discounted_items) # Ensure
non-negative items billed
total_amount = total_items_billed * self.P
return total_amount

def calculate_final_amount(self):
""" Calculate the final amount payable after applying the discount
based on total amount range. """
total_amount = self.calculate_total_amount()

# Determine discount based on total amount range


if total_amount < 1000:
discount = 0.10 # 10%
elif total_amount <= 10000:
discount = 0.15 # 15%
else:
discount = 0.20 # 20%

discount_amount = total_amount * discount


final_amount = total_amount - discount_amount
return round(final_amount, 2) # Round to 2 decimal places

# Example usage

N = int(input("Enter the number of items: "))


P = float(input("Enter the price per item: "))

purchase = Purchase(N, P)
final_amount = purchase.calculate_final_amount()
print("Total amount payable by the customer: $", final_amount)

OUTPUT:

Enter the number of items: 6


Enter the price per item: 34
Total amount payable by the customer: $ 183.6
12. PASSWORD GENERATOR:

class PasswordGenerator:
def __init__(self, name):
self.name = name

def generate_password(self):
""" Generate a password based on the length of the name. """
lc = self.name[-1] # Last character
le = len(self.name) # Length of the name
fc = self.name[0] # First character

if le % 2 == 0: # Even length
password = f"{lc}{le}@{fc}654{lc}"
else: # Odd length
password = f"{lc}{le}!{fc}432{lc}"

return password

# Example usage
name_input = input("Enter the name of a person: ")
password_generator = PasswordGenerator(name_input)
generated_password = password_generator.generate_password()
print("Generated Password:", generated_password)

OUTPUT:

Enter the name of a person: geetha


Generated Password: a6@g654a

You might also like