11/30/24, 9:41 PM my pythonpractice.
ipynb - Colab
unit 3 practice aditya agarwal
1. Merge two Dictionaries
dict1 = {"name": "Aditya Agarwal", "age": 19}
dict2 = {"major": "Computer Science", "grade": "2A"}
# Merge dictionaries
merged_dict = {**dict1, **dict2}
print("Merged Dictionary:", merged_dict)
Merged Dictionary: {'name': 'Aditya Agarwal', 'age': 19, 'major': 'Computer Science', 'grade': '2A'}
2. Find the longest substring without repeating characters.
def longest_unique_substring(s):
char_set = set() # To track characters in the current window
left = 0 # Left pointer of the window
max_length = 0 # Length of the longest substring
for right in range(len(s)):
# If the character is already in the set, move the left pointer
while s[right] in char_set:
char_set.remove(s[left])
left += 1
# Add the character to the set
char_set.add(s[right])
# Update the maximum length
max_length = max(max_length, right - left + 1)
return max_length
# Input string
s = "abcabcbb"
# Find the length of the longest unique substring
result = longest_unique_substring(s)
print("Length of the longest substring without repeating characters:", result)
Length of the longest substring without repeating characters: 3
3. Write a Python program to reverse a string and count the number of vowels in it.
text = "Aditya Agarwal"
# Reverse the string
reversed_text = text[::-1]
print("Reversed String:", reversed_text)
# Count vowels
vowels = "aeiouAEIOU"
vowel_count = sum(1 for char in text if char in vowels)
print("Number of vowels:", vowel_count)
Reversed String: lawragA aytidA
Number of vowels: 6
https://colab.research.google.com/drive/18TuWG5MPlJdOHTQC4trGUovURXwpHGqF#scrollTo=K0h6YE8-Ugxo&printMode=true 3/8
11/30/24, 9:41 PM my pythonpractice.ipynb - Colab
4. Write a Python program to find the union, intersection, and difference of two sets.
# Define two sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Union
union_set = set1.union(set2)
print("Union:", union_set)
# Intersection
intersection_set = set1.intersection(set2)
print("Intersection:", intersection_set)
# Difference
difference_set = set1.difference(set2)
print("Difference:", difference_set)
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference: {1, 2}
5. Write a Python program to find the largest and smallest elements in a tuple.
# Define a tuple
numbers = (10, 20, 5, 30, 15)
# Find the largest and smallest elements
largest = max(numbers)
smallest = min(numbers)
print("Largest element:", largest)
print("Smallest element:", smallest)
Largest element: 30
Smallest element: 5
6. Write a Python program to add a key-value pair, update a value, and delete a key in a dictionary.
# Define a dictionary
student = {"name": "Aditya Agarwal", "age": 18, "major": "CS"}
# Add a key-value pair
student["grade"] = "A"
# Update a value
student["age"] = 19
# Delete a key
del student["major"]
print("Updated Dictionary:", student)
Updated Dictionary: {'name': 'Aditya Agarwal', 'age': 19, 'grade': 'A'}
7. How can you iterate through keys, values, and key-value pairs in a dictionary?
# Define a dictionary
student = {"name": "Aditya Agarwal", "age": 19, "major": "Maths"}
# Iterate through keys
print("Keys:")
for key in student.keys():
print(key)
https://colab.research.google.com/drive/18TuWG5MPlJdOHTQC4trGUovURXwpHGqF#scrollTo=K0h6YE8-Ugxo&printMode=true 4/8
11/30/24, 9:41 PM my pythonpractice.ipynb - Colab
# Iterate through values
print("\nValues:")
for value in student.values():
print(value)
# Iterate through key-value pairs
print("\nKey-Value Pairs:")
for key, value in student.items():
print(f"{key}: {value}")
Keys:
name
age
major
Values:
Aditya Agarwal
19
Maths
Key-Value Pairs:
name: Aditya Agarwal
age: 19
major: Maths
8. Check if a value exist in a set {10, 20, 30, 40, 50}
# Define a set
my_set = {10, 20, 30, 40, 50}
# Value to check
value_to_check = 30
# Check if the value exists in the set
if value_to_check in my_set:
print(f"Value {value_to_check} exists in the set.")
else:
print(f"Value {value_to_check} does not exist in the set.")
Value 30 exists in the set.
9. Access the second largest number in a tuple (10, 20, 30, 40, 50, 20, 10)
# Define a tuple
numbers = (10, 20, 30, 40, 50, 20, 10)
# Remove duplicates by converting the tuple to a set
unique_numbers = set(numbers)
# Sort the unique numbers in descending order
sorted_numbers = sorted(unique_numbers, reverse=True)
# Access the second largest number
if len(sorted_numbers) >= 2:
second_largest = sorted_numbers[1]
print("The second largest number is:", second_largest)
else:
print("The tuple does not have enough unique numbers.")
The second largest number is: 40
10. Count the Frequency of Characters in a String Using a Dictionary “MALAYALAM”.
https://colab.research.google.com/drive/18TuWG5MPlJdOHTQC4trGUovURXwpHGqF#scrollTo=K0h6YE8-Ugxo&printMode=true 5/8
11/30/24, 9:41 PM my pythonpractice.ipynb - Colab
# Input string
text = "MALAYALAM"
# Initialize an empty dictionary to store character counts
char_frequency = {}
# Iterate through each character in the string
for char in text:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
# Print the frequency dictionary
print("Character Frequency:", char_frequency)
Character Frequency: {'M': 2, 'A': 4, 'L': 2, 'Y': 1}
11. Find the symmetric difference between two sets. set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6}
# Define the sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Using the ^ operator
sym_diff = set1 ^ set2
print("Symmetric Difference using ^ operator:", sym_diff)
# Using the symmetric_difference() method
sym_diff_method = set1.symmetric_difference(set2)
print("Symmetric Difference using symmetric_difference() method:", sym_diff_method)
Symmetric Difference using ^ operator: {1, 2, 5, 6}
Symmetric Difference using symmetric_difference() method: {1, 2, 5, 6}
12. Rotate a list by k positions. numbers = [1, 2, 3, 4, 5]
# Define the list and the number of positions to rotate
numbers = [1, 2, 3, 4, 5]
k = 2 # Number of positions to rotate
# Rotate the list
rotated_list = numbers[-k:] + numbers[:-k]
print("Original list:", numbers)
print(f"List after rotating by {k} positions:", rotated_list)
Original list: [1, 2, 3, 4, 5]
List after rotating by 2 positions: [4, 5, 1, 2, 3]
13. Find all unique triplets in a list that sum to zero. nums = [-1, 0, 1, 2, -1, -4]
def three_sum(nums):
nums.sort() # Sort the list
triplets = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]: # Skip duplicates
https://colab.research.google.com/drive/18TuWG5MPlJdOHTQC4trGUovURXwpHGqF#scrollTo=K0h6YE8-Ugxo&printMode=true 6/8
11/30/24, 9:41 PM my pythonpractice.ipynb - Colab
continue
left, right = i + 1, len(nums) - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
if current_sum == 0:
triplets.append([nums[i], nums[left], nums[right]])
# Skip duplicates for `left` and `right`
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
# Move pointers
left += 1
right -= 1
elif current_sum < 0:
left += 1
else:
right -= 1
return triplets
# Input list
nums = [-1, 0, 1, 2, -1, -4]
# Find triplets
result = three_sum(nums)
print("Unique triplets that sum to zero:", result)
Unique triplets that sum to zero: [[-1, -1, 2], [-1, 0, 1]]
14. Find the k most frequent elements in a list. nums = [1, 1, 1, 2, 2, 3]
from collections import Counter
import heapq
def k_most_frequent(nums, k):
# Count the frequency of each element
frequency = Counter(nums)
# Use heapq.nlargest to get the k most frequent elements
most_frequent = heapq.nlargest(k, frequency.keys(), key=frequency.get)
return most_frequent
# Input list and k value
nums = [1, 1, 1, 2, 2, 3]
k = 2
# Find k most frequent elements
result = k_most_frequent(nums, k)
print("The", k, "most frequent elements are:", result)
The 2 most frequent elements are: [1, 2]
https://colab.research.google.com/drive/18TuWG5MPlJdOHTQC4trGUovURXwpHGqF#scrollTo=K0h6YE8-Ugxo&printMode=true 7/8