List and Tuples
Write a Python program to find the second largest number in a list
Method 1
def find_second_largest(numbers):
if len(numbers) < 2:
return None # Not enough elements
largest = second_largest = float('-inf')
for num in numbers:
if num > largest:
second_largest = largest
largest = num
elif num > second_largest and num != largest:
second_largest = num
return second_largest if second_largest != float('-inf') else None
# Example usage
num_list = [12, 45, 67, 89, 34, 67]
second_largest = find_second_largest(num_list)
if second_largest is not None:
print("The second largest number is:", second_largest)
else:
print("A valid second largest number was not found.")
Output
The second largest number is: 67
Method 2: (using set and sorted)
def find_second_largest(numbers):
unique_numbers = list(set(numbers)) # Remove duplicates
if len(unique_numbers) < 2:
return None
unique_numbers.sort(reverse=True)
return unique_numbers[1]
# Example usage
num_list = [10, 20, 40, 40, 30]
print("Second largest number is:", find_second_largest(num_list))
2. Write a Python program to merge two tuples into a dictionary
# Function to merge two tuples into a dictionary
def merge_tuples_to_dict(keys_tuple, values_tuple):
if len(keys_tuple) != len(values_tuple):
print("Tuples must be of the same length.")
return None
return dict(zip(keys_tuple, values_tuple))
# Example tuples
keys = ('a', 'b', 'c')
values = (1, 2, 3)
# Merge and display
result = merge_tuples_to_dict(keys, values)
print("Merged Dictionary:", result)
Output: Merged Dictionary: {'a': 1, 'b': 2, 'c': 3}
2. Dictionaries and Sets:
Write a Python program to count the frequency of each word in a given string using a dictionary.
# Function to count word frequency
def count_word_frequency(text):
# Convert to lowercase and split into words
words = text.lower().split()
# Create an empty dictionary
word_freq = {}
# Count frequency
for word in words:
word = word.strip('.,!?') # Optional: remove punctuation
word_freq[word] = word_freq.get(word, 0) + 1
return word_freq
# Input string
input_string = input("Enter a string: ")
# Count and display result
frequencies = count_word_frequency(input_string)
print("Word Frequencies:")
for word, count in frequencies.items():
print(f"{word}: {count}")
Output:
Enter a string: Hello world! Hello Python world.
Word Frequencies:
hello: 2
world: 2
python: 1
Write a Python program to find the union and intersection of two sets.
# Function to find union and intersection of two sets
def union_and_intersection(set1, set2):
union = set1.union(set2)
intersection = set1.intersection(set2)
return union, intersection
# Example sets
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
# Get union and intersection
union_result, intersection_result = union_and_intersection(set_a, set_b)
# Display results
print("Set A:", set_a)
print("Set B:", set_b)
print("Union:", union_result)
print("Intersection:", intersection_result)
Output:
Set A: {1, 2, 3, 4, 5}
Set B: {4, 5, 6, 7, 8}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}