def hello():
print("
### 1a. Count digits, letters, and special characters in a string
python
def count_chars(s):
digits = letters = special = 0
for char in s:
if char.isdigit():
digits += 1
elif char.isalpha():
letters += 1
else:
special += 1
return digits, letters, special
string = input("Enter a string: ")
d, l, s = count_chars(string)
print(f"Digits: {d}, Letters: {l}, Special characters: {s}")
### 1b. Generate all permutations of a string using recursion
python
def get_permutations(s):
if len(s) == 1:
return [s]
permutations = []
for i in range(len(s)):
first_char = s[i]
remaining_chars = s[:i] + s[i+1:]
for perm in get_permutations(remaining_chars):
permutations.append(first_char + perm)
return permutations
input_str = input("Enter a string: ")
print("All permutations:")
print(get_permutations(input_str))
### 2a. Sum of squares of first N natural numbers
python
def sum_of_squares(n):
return sum(i*i for i in range(1, n+1))
n = int(input("Enter N: "))
print("Sum of squares:", sum_of_squares(n))
### 2b. Simple voting system using dictionaries
python
def voting_system():
candidates = {}
while True:
print("\n1. Vote for a candidate")
print("2. Show results")
print("3. Exit")
choice = input("Enter choice: ")
if choice == '1':
name = input("Enter candidate name: ")
candidates[name] = candidates.get(name, 0) + 1
print("Vote recorded!")
elif choice == '2':
print("\nVoting Results:")
for name, votes in candidates.items():
print(f"{name}: {votes} votes")
elif choice == '3':
break
else:
print("Invalid choice!")
voting_system()
### 3a. Remove duplicates from list while preserving order
python
def remove_duplicates(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
original_list = [1, 2, 3, 2, 4, 3, 5]
print("Original list:", original_list)
print("List after removing duplicates:", remove_duplicates(original_list))
### 3b. Compute grade statistics from file
python
def grade_statistics(filename):
with open(filename, 'r') as file:
marks = [float(line.strip()) for line in file if line.strip()]
if not marks:
return None
return {
'max': max(marks),
'min': min(marks),
'average': sum(marks)/len(marks)
}
stats = grade_statistics('marks.txt')
if stats:
print(f"Max: {stats['max']}, Min: {stats['min']}, Average: {stats['average']:.2f}")
else:
print("No marks found in the file.")
### 4a. Generate all permutations of a list using recursion
python
def list_permutations(lst):
if len(lst) == 1:
return [lst]
perms = []
for i in range(len(lst)):
first = lst[i]
rest = lst[:i] + lst[i+1:]
for p in list_permutations(rest):
perms.append([first] + p)
return perms
input_list = input("Enter list elements separated by space: ").split()
print("All permutations:")
for perm in list_permutations(input_list):
print(perm)
### 4b. Multiple bouncing balls (using Pygame)
python
import pygame
import sys
import random
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Balls")
class Ball:
def __init__(self):
self.radius = random.randint(15, 30)
self.x = random.randint(self.radius, width - self.radius)
self.y = random.randint(self.radius, height - self.radius)
self.dx = random.choice([-4, -3, -2, 2, 3, 4])
self.dy = random.choice([-4, -3, -2, 2, 3, 4])
self.color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
def move(self):
self.x += self.dx
self.y += self.dy
if self.x <= self.radius or self.x >= width - self.radius:
self.dx = -self.dx
if self.y <= self.radius or self.y >= height - self.radius:
self.dy = -self.dy
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
balls = [Ball() for _ in range(5)]
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((0, 0, 0))
for ball in balls:
ball.move()
ball.draw()
pygame.display.flip()
clock.tick(60)
### 5a. Factorial using recursion and iteration
python
def factorial_recursive(n):
return 1 if n == 0 else n * factorial_recursive(n-1)
def factorial_iterative(n):
result = 1
for i in range(1, n+1):
result *= i
return result
num = int(input("Enter a number: "))
print(f"Recursive factorial: {factorial_recursive(num)}")
print(f"Iterative factorial: {factorial_iterative(num)}")
### 5b. Math utility package
Create a directory structure:
math_utils/
__init__.py
prime.py
gcd_lcm.py
*prime.py*:
python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
*gcd_lcm.py*:
python
def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b)
*_init_.py*:
python
from .prime import is_prime
from .gcd_lcm import gcd, lcm
### 6a. Copy list using iteration and slicing
python
original_list = [1, 2, 3, 4, 5]
# Using iteration
copied_list_iter = []
for item in original_list:
copied_list_iter.append(item)
# Using slicing
copied_list_slice = original_list[:]
print("Original:", original_list)
print("Copied (iteration):", copied_list_iter)
print("Copied (slicing):", copied_list_slice)
### 7a. Group anagrams using dictionaries
python
def group_anagrams(words):
anagrams = {}
for word in words:
sorted_word = ''.join(sorted(word))
if sorted_word in anagrams:
anagrams[sorted_word].append(word)
else:
anagrams[sorted_word] = [word]
return list(anagrams.values())
word_list = ["listen", "silent", "enlist", "hello", "world", "dlrow"]
print("Anagram groups:", group_anagrams(word_list))
### 8b. Serialize dictionary with pickle
python
import pickle
def serialize_employees(employees, filename):
with open(filename, 'wb') as file:
pickle.dump(employees, file)
def deserialize_employees(filename):
with open(filename, 'rb') as file:
return pickle.load(file)
# Example usage
employees = {
'101': {'name': 'John', 'position': 'Manager', 'salary': 50000},
'102': {'name': 'Alice', 'position': 'Developer', 'salary': 45000}
}
serialize_employees(employees, 'employees.pkl')
loaded_employees = deserialize_employees('employees.pkl')
print("Loaded employees:", loaded_employees)
### 9a. Tower of Hanoi
python
def tower_of_hanoi(n, source, target, auxiliary):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n-1, source, auxiliary, target)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n-1, auxiliary, target, source)
disks = int(input("Enter number of disks: "))
tower_of_hanoi(disks, 'A', 'C', 'B')
### 10b. Shift list elements left
python
def shift_left(lst):
if len(lst) <= 1:
return lst
return lst[1:] + [lst[0]]
original = [1, 2, 3, 4, 5]
print("Original:", original)
print("Shifted left:", shift_left(original))
### 11b. Serialize/deserialize with pickle
python
import pickle
def serialize(data, filename):
with open(filename, 'wb') as file:
pickle.dump(data, file)
def deserialize(filename):
with open(filename, 'rb') as file:
return pickle.load(file)
# Example usage
data = {'key1': 'value1', 'key2': [1, 2, 3]}
serialize(data, 'data.pkl')
loaded_data = deserialize('data.pkl')
print("Loaded data:", loaded_data)
### 12b. Phonebook backup/restore with pickle
python
import pickle
def backup_phonebook(phonebook, filename):
with open(filename, 'wb') as file:
pickle.dump(phonebook, file)
print("Backup completed.")
def restore_phonebook(filename):
try:
with open(filename, 'rb') as file:
return pickle.load(file)
except FileNotFoundError:
print("Backup file not found.")
return {}
# Example usage
phonebook = {'John': '123-4567', 'Alice': '987-6543'}
backup_phonebook(phonebook, 'phonebook.bak')
restored = restore_phonebook('phonebook.bak')
print("Restored phonebook:", restored)
### 13a. Contact manager with pickle
python
import pickle
def save_contacts(contacts, filename='contacts.dat'):
with open(filename, 'wb') as file:
pickle.dump(contacts, file)
def load_contacts(filename='contacts.dat'):
try:
with open(filename, 'rb') as file:
return pickle.load(file)
except FileNotFoundError:
return {}
def contact_manager():
contacts = load_contacts()
while True:
print("\n1. Add contact")
print("2. View contacts")
print("3. Search contact")
print("4. Exit")
choice = input("Enter choice: ")
if choice == '1':
name = input("Enter name: ")
phone = input("Enter phone: ")
email = input("Enter email: ")
contacts[name] = {'phone': phone, 'email': email}
save_contacts(contacts)
print("Contact saved!")
elif choice == '2':
print("\nContacts:")
for name, info in contacts.items():
print(f"{name}: {info['phone']}, {info['email']}")
elif choice == '3':
name = input("Enter name to search: ")
if name in contacts:
print(f"Found: {contacts[name]['phone']}, {contacts[name]['email']}")
else:
print("Contact not found.")
elif choice == '4':
break
else:
print("Invalid choice!")
contact_manager()
### 14a. Inventory management with nested dictionaries
python
def inventory_management():
inventory = {}
while True:
print("\n1. Add item")
print("2. View inventory")
print("3. Update quantity")
print("4. Exit")
choice = input("Enter choice: ")
if choice == '1':
item_id = input("Enter item ID: ")
name = input("Enter item name: ")
price = float(input("Enter price: "))
quantity = int(input("Enter quantity: "))
inventory[item_id] = {'name': name, 'price': price, 'quantity': quantity}
print("Item added!")
elif choice == '2':
print("\nInventory:")
for item_id, details in inventory.items():
print(f"{item_id}: {details['name']}, ${details['price']}, Qty: {details['quantity']}")
elif choice == '3':
item_id = input("Enter item ID: ")
if item_id in inventory:
change = int(input("Enter quantity change (+/-): "))
inventory[item_id]['quantity'] += change
print("Quantity updated!")
else:
print("Item not found.")
elif choice == '4':
break
else:
print("Invalid choice!")
inventory_management()
### 14b. Draw shapes with Pygame
python
import pygame
import sys
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Shape Drawer")
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(BLACK)
# Draw rectangle
pygame.draw.rect(screen, RED, (100, 100, 200, 150), 2)
# Draw circle
pygame.draw.circle(screen, GREEN, (400, 300), 100, 2)
# Draw line
pygame.draw.line(screen, BLUE, (700, 100), (700, 500), 2)
pygame.display.flip()
### 16a. Check Armstrong number
python
def is_armstrong(num):
num_str = str(num)
length = len(num_str)
total = sum(int(digit)**length for digit in num_str)
return total == num
number = int(input("Enter a number: "))
if is_armstrong(number):
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
### 16b. Exception handling with logging
python
import logging
logging.basicConfig(filename='error.log', level=logging.ERROR,
format='%(asctime)s - %(levelname)s - %(message)s')
def divide_numbers():
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 / num2
print(f"Result: {result}")
except ValueError:
print("Please enter valid numbers!")
logging.error("ValueError occurred - Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero!")
logging.error("ZeroDivisionError occurred - Division by zero")
except Exception as e:
print(f"An error occurred: {e}")
logging.error(f"Unexpected error: {str(e)}")
divide_numbers()
### 17a. File compression with zipfile
python
import zipfile
import sys
import os
def compress_files(zip_name, files):
try:
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for file in files:
if os.path.exists(file):
zipf.write(file)
print(f"Added {file} to {zip_name}")
else:
print(f"File not found: {file}")
print("Compression completed successfully!")
except Exception as e:
print(f"Error during compression: {e}")
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python compress.py output.zip file1 file2 ...")
else:
output_file = sys.argv[1]
files_to_compress = sys.argv[2:]
compress_files(output_file, files_to_compress)
")
Comments
Post a Comment