Part-A
1. String Slicing in Python:
String slicing allows accessing a part of the string using a range of indices. The syntax is
`string[start:end]`. The slice starts from the `start` index and stops at `end-1`.
Example:
text = "Hello, World!"
slice_text = text[0:5] # Slices from index 0 to 4 (first 5 characters)
print(slice_text) # Output: Hello
2. Difference between `append()` and `extend()` in Python lists:
- `append()`: Adds its argument as a single element to the end of a list. The length of the list increases
by one.
- `extend()`: Iterates over its argument, adding each element to the list. The length of the list increases
by however many elements were in the iterable.
Example:
lst = [1, 2, 3]
lst.append([4, 5]) # [1, 2, 3, [4, 5]]
lst.extend([6, 7]) # [1, 2, 3, [4, 5], 6, 7]
3. Sum of elements in a list using a loop:
Example:
lst = [1, 2, 3, 4, 5]
total = 0
for num in lst:
total += num
print(total) # Output: 15
4. Adding a new key-value pair to a dictionary:
To add a new key-value pair, you can simply assign a value to a key like so:
Example:
student = {"name": "Alice", "age": 21}
student["grade"] = "A"
print(student) # Output: {'name': 'Alice', 'age': 21, 'grade': 'A'}
5. Python program to sort a list in descending order using `sort()`:
You can use the `sort()` method with the `reverse=True` argument.
Example:
lst = [3, 1, 4, 1, 5, 9]
lst.sort(reverse=True)
print(lst) # Output: [9, 5, 4, 3, 1, 1]
---
Part-B
6(a). Program to separate prefix and suffix, create a dictionary ignoring vowels:
def process_string(input_string):
# Split into prefix and suffix
prefix, suffix = input_string.split('@')
# Create dictionary for number of unique characters
unique_chars = len(set(suffix) - set('aeiouAEIOU'))
# Find longest word
words = suffix.split()
longest_word = max(words, key=len) if words else ""
# Return result as dictionary
result = {"unique_characters": unique_chars, "longest_word": longest_word}
return result
input_string = "prefix@suffix without vowels"
result = process_string(input_string)
print(result)
6(b) Program to eliminate first and last characters, reverse and check palindrome:
def process_string(input_string):
# Step 1: Extract first word
first_word = input_string.split()[0]
# Step 2: Eliminate first and last characters gradually
trimmed_string = first_word[1:-1] if len(first_word) > 1 else first_word
# Step 3: Reverse the string
reversed_string = trimmed_string[::-1]
# Step 4: Check if palindrome
is_palindrome = trimmed_string == reversed_string
return {"reversed": reversed_string, "palindrome_check": is_palindrome}
input_string = "level racecar"
result = process_string(input_string)
print(result)
7 (a) Implement a Python program that prepares a retail bill.
- The task involves adding items to a list and calculating the total bill using list comprehension.
items = []
total_price = 0
while True:
item = input("Enter item (or 'done' to finish): ")
if item == 'done':
break
price = float(input(f"Enter price for {item}: "))
items.append({'item': item, 'price': price})
total_price = sum([item['price'] for item in items])
print(f"Total bill: {total_price}")
Analysis of list slicing, looping, mutability:
- List slicing allows for efficient retrieval of specific elements.
- Looping through lists can impact performance depending on the list's size.
- Mutability allows updating the list directly, making it suitable for dynamic data like a shopping list.
7(b) Write a Python program to create a dictionary of student marks.
- The program should store, update, delete, and retrieve marks.
student_marks = {}
while True:
name = input("Enter student name (or 'done' to finish): ")
if name == 'done':
break
marks = float(input(f"Enter marks for {name}: "))
student_marks[name] = marks
# Update example
student_marks['Alice'] = 95 # Updates Alice's marks
# Delete example
del student_marks['Bob'] # Deletes Bob's entry
# Retrieve example
print(student_marks.get('Alice', 'No record found'))
Analysis of dictionary operations:
- Update and retrieve operations are generally fast due to hashing, but delete can be slower for large
datasets.
- Handling large datasets requires efficient memory management.
PART C (1x14 = 14 Marks)
8. (a) Implement an email filtering system.
- The system should find spam emails using string slicing and methods, and implement linear and
binary search for specific keywords.
emails = ["Special offer just for you!", "Meeting reminder", "Win a free trip!"]
keyword = "offer"
# Linear Search
for email in emails:
if keyword in email:
print(f"Keyword found in: {email}")
# Binary Search (after sorting emails)
emails.sort()
low, high = 0, len(emails) - 1
while low <= high:
mid = (low + high) // 2
if keyword in emails[mid]:
print(f"Keyword found in: {emails[mid]}")
break
elif keyword < emails[mid]:
high = mid - 1
else:
low = mid + 1
Analysis of search algorithms:
- Linear Search has O(n) time complexity, making it slower for large datasets.
- Binary Search requires sorting but has O(log n) complexity, making it more efficient for large datasets
8(b) Write a Python program to implement an inventory management system using dictionaries.
inventory = {}
while True:
action = input("Add/Update/Delete/Search/Report (or 'done' to finish): ")
if action == 'done':
break
if action == 'Add':
item = input("Enter item: ")
price = float(input(f"Enter price for {item}: "))
qty = int(input(f"Enter quantity for {item}: "))
inventory[item] = {'price': price, 'quantity': qty}
elif action == 'Update':
item = input("Enter item to update: ")
inventory[item]['price'] = float(input(f"New price for {item}: "))
elif action == 'Delete':
item = input("Enter item to delete: ")
del inventory[item]
elif action == 'Search':
item = input("Enter item to search: ")
print(inventory.get(item, "Item not found"))
elif action == 'Report':
total_value = sum(item['price'] * item['quantity'] for item in inventory.values())
print(f"Total inventory value: {total_value}")
Program efficiency and validation:
- Dictionaries offer fast access and updates but can consume more memory.
- Ensure input validation to handle erroneous data inputs properly.