1. Reverse a String
Problem:
Write a function to reverse a string.
Function Signature:
def reverse_string(s: str) -> str:
return s[::-1] # Uses slicing to reverse the string
# Example usage
print(reverse_string("hello")) # Output: "olleh"
The function reverse_string(s: str) -> str
is a Python function that takes a string s
as input and returns its reversed version.
Explanation:
s: str
→ This specifies that the function takes a string as an argument.-> str
→ This indicates that the function returns a string.
How It Works:
s[::-1]
is a slicing technique where:[::-1]
means "take the string from start to end with a step of -1," effectively reversing it.
This method is efficient and concise for reversing strings in Python.
2. Find the Second Largest Number
Problem:
Given a list of numbers, find the second largest number.
Function Signature:
from typing import List
def second_largest(nums: List[int]) -> int:
if len(nums) < 2:
raise ValueError("List must contain at least two distinct elements")
first, second = float('-inf'), float('-inf')
for num in nums:
if num > first:
second, first = first, num # Update both first and second
elif first > num > second:
second = num # Update second if it's smaller than first but greater than current second
if second == float('-inf'):
raise ValueError("List must contain at least two distinct elements")
return second
# Example usage
print(second_largest([10, 20, 4, 45, 99])) # Output: 45
The function second_largest(nums: List[int]) -> int
is intended to find and return the second-largest number in a given list of integers.
Explanation:
nums: List[int]
→ The function takes a list of integers as input.-> int
→ The function returns an integer, which is the second-largest number in the list.
How It Works:
Initialize
first
andsecond
with negative infinity (-inf
) to track the largest and second-largest numbers.Iterate through the list:
If a number is greater than
first
, updatesecond
withfirst
andfirst
with the current number.If a number is smaller than
first
but greater thansecond
, updatesecond
.
If
second
remains-inf
, it means there was no valid second-largest number, so raise an exception.
Key Points:
num
is declared implicitly inside the loop.Python automatically assigns
num
the value of each element innums
as it loops.The scope of
num
is within the loop unless used outside.
If you try to access num
before the loop starts, it won’t exist. But after the loop, it will retain the last value assigned.
3. Check if a String is a Palindrome
Problem:
Check if the given string is a palindrome (reads the same forward and backward).
Function Signature:
def is_palindrome(s: str) -> bool:
return s == s[::-1] # Compare the string with its reverse
# Example usage
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("hello")) # Output: False
Explanation:
s[::-1]
reverses the string.The function returns
True
if the original string is equal to its reversed version; otherwise, it returnsFalse
.
Edge Cases:
Empty string (
""
) → Considered a palindrome (True
).Single character (
"a"
) → Always a palindrome (True
).Case sensitivity →
"Racecar"
is different from"racecar"
, so may need.lower()
.Ignoring non-alphanumeric characters → Use
filter(str.isalnum, s)
if needed.
Here's an enhanced version of the is_palindrome
function that:
Ignores spaces
Ignores case sensitivity
Ignores non-alphanumeric characters (like punctuation)
Updated Function:
import re
def is_palindrome(s: str) -> bool:
# Remove non-alphanumeric characters and convert to lowercase
cleaned_s = ''.join(filter(str.isalnum, s)).lower()
# Check if the cleaned string is a palindrome
return cleaned_s == cleaned_s[::-1]
# Example usage
print(is_palindrome("A man, a plan, a canal: Panama")) # Output: True
print(is_palindrome("No lemon, no melon!")) # Output: True
print(is_palindrome("Hello, World!")) # Output: False
Explanation:
filter(str.isalnum, s)
:The
filter()
function iterates throughs
, keeping only characters that pass thestr.isalnum
check.str.isalnum()
returnsTrue
for letters and digits, filtering out spaces, punctuation, and symbols.
Example:
s = "A man, a plan, a canal: Panama"
print(''.join(filter(str.isalnum, s))) # Output: "AmanaplanacanalPanama"
.lower()
:Converts the string to lowercase to ensure case insensitivity.
"Racecar"
and"racecar"
should be treated as the same word.
[::-1]
:- This reverses the string and checks for equality.
Key Points ::
1. filter(str.isalnum, s)
filter(str.isalnum, s)
keeps only alphanumeric characters froms
, removing spaces and punctuation.
2. ''.join(...)
''.join(...)
combines the filtered characters into a single string without any separator.The
''
(empty string) is the separator.Example:
s = "Hello, World!" cleaned_s = ''.join(filter(str.isalnum, s)) print(cleaned_s) # Output: "HelloWorld"
If we used
'-'.join(...)
, the output would be"H-e-l-l-o-W-o-r-l-d"
.
3. .lower()
- Converts the cleaned string to lowercase.
4. Count the Occurrences of Each Character
Problem:
Given a string, count the occurrence of each character.
Function Signature:
from collections import Counter
def char_count(s: str) -> Dict[str, int]:
return dict(Counter(s))
print(char_count("hello")) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
Counter(s)
automatically creates a dictionary of character counts.
5. Find the Missing Number in a List
Problem:
Given a list containing numbers from 1 to N
, with one missing number, find the missing number.
Function Signature:
from typing import List
def missing_number(arr: List[int], n: int) -> int:
total_sum = n * (n + 1) // 2 # Sum of first n natural numbers
arr_sum = sum(arr) # Sum of elements in the given array
return total_sum - arr_sum # The missing number
# Example usage
print(missing_number([1, 2, 3, 5], 5)) # Output: 4
print(missing_number([1, 2, 4, 5, 6], 6)) # Output: 3
Explanation
Formula for the sum of first
n
natural numbers:{total_sum} = {n (n + 1)}/{2}
- Example: If
n = 5
, sum should be1 + 2 + 3 + 4 + 5 = 15
.
- Example: If
Find the sum of given elements (
sum(arr)
)- Example: If
arr = [1, 2, 3, 5]
, sum is1 + 2 + 3 + 5 = 11
.
- Example: If
Compute the missing number
total_sum - sum(arr)
gives the missing number.15 - 11 = 4
, so4
is the missing number.
6. Check if Two Strings are Anagrams
Problem:
Check if two given strings are anagrams (contain the same characters in a different order).
Function Signature:
def is_anagram(s1: str, s2: str) -> bool:
return sorted(s1) == sorted(s2) # Sort both strings and compare
# Example usage
print(is_anagram("listen", "silent")) # Output: True
print(is_anagram("hello", "world")) # Output: False
7. Find the Longest Substring Without Repeating Characters
Problem:
Given a string, find the length of the longest substring without repeating characters.
Function Signature:
def longest_unique_substring(s: str) -> int:
char_index = {} # Stores the last seen index of characters
max_length = 0
start = 0 # Left boundary of the window
for end, char in enumerate(s):
if char in char_index and char_index[char] >= start:
start = char_index[char] + 1 # Move the start to avoid repetition
char_index[char] = end # Update last seen index of character
max_length = max(max_length, end - start + 1) # Update max length
return max_length
# Example usage
print(longest_unique_substring("abcabcbb")) # Output: 3 ("abc")
print(longest_unique_substring("bbbbb")) # Output: 1 ("b")
print(longest_unique_substring("pwwkew")) # Output: 3 ("wke")
Explanation (Sliding Window + HashMap)
Use a dictionary (
char_index
) to track the last seen index of each character.Expand the window (
end
pointer moves right):- If the character is already in the dictionary and inside the window, move
start
tochar_index[char] + 1
(avoiding repetition).
- If the character is already in the dictionary and inside the window, move
Update max length at each step.
8.Merge two Sorted Lists
Problem:
Given two sorted lists, merge them into one sorted list.
Function Signature:
from typing import List
def merge_sorted_lists(lst1: List[int], lst2: List[int]) -> List[int]:
merged = []
i, j = 0, 0 # Pointers for both lists
# Merge both lists while elements remain in both
while i < len(lst1) and j < len(lst2):
if lst1[i] < lst2[j]:
merged.append(lst1[i])
i += 1
else:
merged.append(lst2[j])
j += 1
# Add remaining elements from lst1
while i < len(lst1):
merged.append(lst1[i])
i += 1
# Add remaining elements from lst2
while j < len(lst2):
merged.append(lst2[j])
j += 1
return merged
# Example usage
print(merge_sorted_lists([1, 3, 5], [2, 4, 6])) # Output: [1, 2, 3, 4, 5, 6]
print(merge_sorted_lists([1, 2, 7], [3, 5, 6])) # Output: [1, 2, 3, 5, 6, 7]
Explanation
Use two pointers (
i
,j
) to traverse both lists.Compare elements from both lists:
Append the smaller element to
merged[]
.Move the pointer in the list where the element was taken from.
Append remaining elements from
lst1
orlst2
after the loop.
Alternative Using heapq.merge()
(Python Built-in)
import heapq
def merge_sorted_lists(lst1: List[int], lst2: List[int]) -> List[int]:
return list(heapq.merge(lst1, lst2)) # Efficient merging of sorted lists
print(merge_sorted_lists([1, 3, 5], [2, 4, 6])) # Output: [1, 2, 3, 4, 5, 6]
- Uses a heap-based approach for merging efficiently.
9. Sum of Digits of a Number
Problem:
Write a function that takes an integer and returns the sum of its digits.
def sum_of_digits(n: int) -> int:
return sum(int(digit) for digit in str(n))
# Example usage:
print(sum_of_digits(1234)) # Output: 10
10. Check if a Number is Prime
Problem:
Write a function that checks if a given number is prime.
def is_prime(n: int) -> bool:
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# Example usage:
print(is_prime(11)) # Output: True
print(is_prime(10)) # Output: False
11. Find Factorial of a Number
Problem:
Write a function that calculates the factorial of a given number.
def factorial(n: int) -> int:
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result
# Example usage:
print(factorial(5)) # Output: 120
12. Check if a Year is a Leap Year
Problem:
Write a function that checks if a given year is a leap year.
def is_leap_year(year: int) -> bool:
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
# Example usage:
print(is_leap_year(2024)) # Output: True
print(is_leap_year(1900)) # Output: False
13. Find the Largest Element in a List
Problem:
Write a function to find the largest element in a list.
def find_max(lst: list) -> int:
return max(lst)
# Example usage:
print(find_max([10, 20, 30, 40, 50])) # Output: 50
14. Remove Duplicates from a List
Problem:
Write a function to remove duplicates from a list while maintaining the order.
def remove_duplicates(lst: list) -> list:
seen = set()
return [x for x in lst if not (x in seen or seen.add(x))]
# Example usage:
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # Output: [1, 2, 3, 4, 5]
15. Find Common Elements in Two Lists
Problem:
Write a function to find the common elements in two lists.
def common_elements(lst1: list, lst2: list) -> list:
return list(set(lst1) & set(lst2))
# Example usage:
print(common_elements([1, 2, 3, 4], [3, 4, 5, 6])) # Output: [3, 4]
16. Rotate an Array to the Right by K Places
Problem:
Write a function to rotate a list to the right by k
places.
def rotate_right(lst: list, k: int) -> list:
k = k % len(lst) # Ensure k is within bounds
return lst[-k:] + lst[:-k]
# Example usage:
print(rotate_right([1, 2, 3, 4, 5], 2)) # Output: [4, 5, 1, 2, 3]
17. Check if a Sentence is a Pangram
Problem:
Write a function to check if a sentence contains all letters of the English alphabet.
import string
def is_pangram(s: str) -> bool:
return set(string.ascii_lowercase).issubset(set(s.lower()))
# Example usage:
print(is_pangram("The quick brown fox jumps over the lazy dog")) # Output: True
print(is_pangram("Hello World")) # Output: False
18. Count the Number of Words in a Sentence
Problem:
Write a function to count the number of words in a given sentence.
def word_count(s: str) -> int:
return len(s.split())
# Example usage:
print(word_count("Python is a great programming language")) # Output: 6
19. Check if a List is Sorted
Problem:
Write a function to check if a list is sorted in ascending order.
def is_sorted(lst: list) -> bool:
return lst == sorted(lst)
# Example usage:
print(is_sorted([1, 2, 3, 4, 5])) # Output: True
print(is_sorted([1, 3, 2, 4, 5])) # Output: False
20. Find the Missing Number in an Array
Problem:
Given a list of numbers from 1 to N
with one number missing, find the missing number.
def missing_number(arr: list, n: int) -> int:
expected_sum = n * (n + 1) // 2
actual_sum = sum(arr)
return expected_sum - actual_sum
# Example usage:
print(missing_number([1, 2, 4, 5, 6], 6)) # Output: 3
21. Find the Intersection of Two Sorted Arrays
Problem:
Find the common elements between two sorted arrays.
def intersect_sorted(arr1: list, arr2: list) -> list:
i, j = 0, 0
result = []
while i < len(arr1) and j < len(arr2):
if arr1[i] == arr2[j]:
result.append(arr1[i])
i += 1
j += 1
elif arr1[i] < arr2[j]:
i += 1
else:
j += 1
return result
# Example usage:
print(intersect_sorted([1, 2, 3, 5], [2, 3, 4, 5])) # Output: [2, 3, 5]
22. Find the First Non-Repeating Character in a String
Problem:
Given a string, find the first character that appears only once.
from collections import Counter
def first_unique_char(s: str) -> str:
char_count = Counter(s)
for char in s:
if char_count[char] == 1:
return char
return None # If no unique character found
# Example usage:
print(first_unique_char("swiss")) # Output: "w"
23. Find the Maximum Subarray Sum (Kadane's Algorithm)
Problem:
Find the contiguous subarray with the maximum sum.
def max_subarray_sum(arr: list) -> int:
max_sum = float('-inf')
current_sum = 0
for num in arr:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
# Example usage:
print(max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4])) # Output: 6
24. Reverse the Words in a String
Problem:
Given a sentence, reverse the order of words.
def reverse_words(sentence: str) -> str:
return ' '.join(sentence.split()[::-1])
# Example usage:
print(reverse_words("Hello World Python")) # Output: "Python World Hello"
25. Find All Pairs in an Array that Sum to a Given Number
Problem:
Find all pairs in an array whose sum equals a given target.
def find_pairs(arr: list, target: int) -> list:
seen = set()
result = []
for num in arr:
diff = target - num
if diff in seen:
result.append((diff, num))
seen.add(num)
return result
# Example usage:
print(find_pairs([1, 2, 3, 4, 5], 6)) # Output: [(2, 4), (1, 5)]
26. Count Vowels and Consonants in a String
Problem:
Write a function to count vowels and consonants in a given string.
def count_vowels_consonants(s: str) -> dict:
vowels = "aeiouAEIOU"
v_count = sum(1 for char in s if char in vowels)
c_count = sum(1 for char in s if char.isalpha() and char not in vowels)
return {"vowels": v_count, "consonants": c_count}
# Example usage:
print(count_vowels_consonants("hello world")) # Output: {'vowels': 3, 'consonants': 7}
27. Convert Roman Numerals to Integer
Problem:
Convert a given Roman numeral to an integer.
def roman_to_integer(s: str) -> int:
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
prev_value = 0
for char in s[::-1]: # Reverse iterate
value = roman_dict[char]
if value < prev_value:
total -= value
else:
total += value
prev_value = value
return total
# Example usage:
print(roman_to_integer("IX")) # Output: 9
print(roman_to_integer("MCMXCIV")) # Output: 1994
28. Find the Longest Common Prefix in a List of Strings
Problem:
Find the longest common prefix in a list of words.
def longest_common_prefix(words: list) -> str:
if not words:
return ""
prefix = words[0]
for word in words[1:]:
while not word.startswith(prefix):
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
# Example usage:
print(longest_common_prefix(["flower", "flow", "flight"])) # Output: "fl"
print(longest_common_prefix(["dog", "racecar", "car"])) # Output: ""
29. Find the Kth Largest Element in an Array
Problem:
Find the k
th largest element in an unsorted array.
import heapq
def kth_largest(arr: list, k: int) -> int:
return heapq.nlargest(k, arr)[-1]
# Example usage:
print(kth_largest([3, 2, 1, 5, 6, 4], 2)) # Output: 5
30. Find the Sum of All Elements in a List
Problem:
Write a function that takes a list of numbers and returns the sum of all elements.
def sum_of_list(lst: list) -> int:
return sum(lst)
# Example usage:
print(sum_of_list([1, 2, 3, 4, 5])) # Output: 15
31. Find the Smallest Element in a List
Problem:
Write a function to find the smallest element in a list.
def find_min(lst: list) -> int:
return min(lst)
# Example usage:
print(find_min([10, 20, 30, 5, 50])) # Output: 5
32. Find the Fibonacci Sequence Up to N Terms
Problem:
Write a function to generate the Fibonacci sequence up to n
terms.
def fibonacci(n: int) -> list:
fib_seq = [0, 1]
for _ in range(n - 2):
fib_seq.append(fib_seq[-1] + fib_seq[-2])
return fib_seq[:n]
# Example usage:
print(fibonacci(7)) # Output: [0, 1, 1, 2, 3, 5, 8]
33. Convert Celsius to Fahrenheit
Problem:
Write a function that converts a temperature from Celsius to Fahrenheit.
def celsius_to_fahrenheit(celsius: float) -> float:
return (celsius * 9/5) + 32
# Example usage:
print(celsius_to_fahrenheit(25)) # Output: 77.0
34. Reverse a List
Problem:
Write a function that takes a list and returns it reversed.
def reverse_list(lst: list) -> list:
return lst[::-1]
# Example usage:
print(reverse_list([1, 2, 3, 4, 5])) # Output: [5, 4, 3, 2, 1]
35. Count Vowels in a String
Problem:
Write a function to count the number of vowels (a, e, i, o, u
) in a string.
def count_vowels(s: str) -> int:
return sum(1 for char in s.lower() if char in "aeiou")
# Example usage:
print(count_vowels("Hello World")) # Output: 3
36. Find the Intersection of Two Lists
Problem:
Write a function that finds the common elements between two lists.
def list_intersection(lst1: list, lst2: list) -> list:
return list(set(lst1) & set(lst2))
# Example usage:
print(list_intersection([1, 2, 3, 4], [3, 4, 5, 6])) # Output: [3, 4]
37. Find the Union of Two Lists
Problem:
Write a function that returns the union of two lists (without duplicates).
def list_union(lst1: list, lst2: list) -> list:
return list(set(lst1) | set(lst2))
# Example usage:
print(list_union([1, 2, 3], [3, 4, 5])) # Output: [1, 2, 3, 4, 5]
38. Find the GCD (Greatest Common Divisor) of Two Numbers
Problem:
Write a function to compute the greatest common divisor (GCD) of two numbers.
import math
def find_gcd(a: int, b: int) -> int:
return math.gcd(a, b)
# Example usage:
print(find_gcd(48, 18)) # Output: 6
39. Check if a String is an Isogram
Problem:
An isogram is a word where no letter appears more than once. Write a function to check if a word is an isogram.
def is_isogram(s: str) -> bool:
return len(s) == len(set(s.lower()))
# Example usage:
print(is_isogram("machine")) # Output: True
print(is_isogram("programming")) # Output: False
40. Find the Frequency of Each Element in a List
Problem:
Given a list of numbers, count the frequency of each unique element.
from collections import Counter
def frequency_count(lst: list) -> dict:
return dict(Counter(lst))
# Example usage:
print(frequency_count([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]))
# Output: {1: 1, 2: 2, 3: 3, 4: 4}
41. Reverse a Linked List
Problem:
Reverse a singly linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_linked_list(head: ListNode) -> ListNode:
prev, current = None, head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
# Example usage:
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
new_head = reverse_linked_list(head)
while new_head:
print(new_head.val, end=" ") # Output: 4 3 2 1
new_head = new_head.next
42. Implement a Stack using a List
Problem:
Implement a stack with push, pop, and peek operations.
class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
return self.stack.pop() if self.stack else None
def peek(self):
return self.stack[-1] if self.stack else None
# Example usage:
s = Stack()
s.push(10)
s.push(20)
print(s.pop()) # Output: 20
print(s.peek()) # Output: 10
43. Implement a Queue using a List
Problem:
Implement a queue with enqueue, dequeue, and front operations.
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
return self.queue.pop(0) if self.queue else None
def front(self):
return self.queue[0] if self.queue else None
# Example usage:
q = Queue()
q.enqueue(5)
q.enqueue(10)
print(q.dequeue()) # Output: 5
print(q.front()) # Output: 10
44. Find the GCD of Two Numbers
Problem:
Find the Greatest Common Divisor (GCD) of two numbers.
import math
def gcd(a: int, b: int) -> int:
return math.gcd(a, b)
# Example usage:
print(gcd(54, 24)) # Output: 6
45. Find the LCM of Two Numbers
Problem:
Find the Least Common Multiple (LCM) of two numbers.
def lcm(a: int, b: int) -> int:
return abs(a * b) // math.gcd(a, b)
# Example usage:
print(lcm(12, 18)) # Output: 36
46. Implement a Binary Search Algorithm
Problem:
Implement binary search to find a target in a sorted list.
def binary_search(arr: list, target: int) -> int:
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Not found
# Example usage:
print(binary_search([1, 2, 3, 4, 5, 6], 4)) # Output: 3
47. Check if Two Strings are Rotations of Each Other
Problem:
Check if one string is a rotation of another.
def are_rotations(s1: str, s2: str) -> bool:
return len(s1) == len(s2) and s1 in s2 + s2
# Example usage:
print(are_rotations("abcde", "cdeab")) # Output: True
print(are_rotations("abc", "bca")) # Output: True
print(are_rotations("abc", "bac")) # Output: False
48. Check if a String has Balanced Parentheses
Problem:
Check if a string containing parentheses is balanced.
def is_balanced(s: str) -> bool:
stack = []
pairs = {')': '(', '}': '{', ']': '['}
for char in s:
if char in "({[":
stack.append(char)
elif char in ")}]":
if not stack or stack.pop() != pairs[char]:
return False
return not stack
# Example usage:
print(is_balanced("{[()]}")) # Output: True
print(is_balanced("{[(])}")) # Output: False
49. Find the Most Frequent Element in a List
Problem:
Find the element that occurs most frequently in a list.
from collections import Counter
def most_frequent(lst: list) -> int:
return Counter(lst).most_common(1)[0][0]
# Example usage:
print(most_frequent([1, 3, 2, 3, 4, 3, 5, 3])) # Output: 3
50. Generate Fibonacci Sequence up to N Terms
Problem:
Generate the first N Fibonacci numbers.
def fibonacci(n: int) -> list:
fib = [0, 1]
for _ in range(n - 2):
fib.append(fib[-1] + fib[-2])
return fib[:n]
# Example usage:
print(fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
51. Extract Emails from a Text File
Problem:
Write a function that reads a text file and extracts all email addresses.
import re
def extract_emails(filename: str) -> list:
with open(filename, "r") as file:
content = file.read()
return re.findall(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", content)
# Example usage:
# Create a file `sample.txt` with emails inside before running
print(extract_emails("sample.txt"))
52. Replace Words in a File
Problem:
Write a function that replaces a given word in a text file with another word.
def replace_word(filename: str, old_word: str, new_word: str):
with open(filename, "r") as file:
content = file.read()
content = content.replace(old_word, new_word)
with open(filename, "w") as file:
file.write(content)
# Example usage:
# Before running, create a `text.txt` file with content
replace_word("text.txt", "oldword", "newword")
53. Count Word Frequency in a String
Problem:
Write a function that counts the occurrence of each word in a given text.
from collections import Counter
def word_frequency(text: str) -> dict:
words = text.lower().split()
return dict(Counter(words))
# Example usage:
print(word_frequency("Python is easy. Python is powerful."))
# Output: {'python': 2, 'is': 2, 'easy.': 1, 'powerful.': 1}
54. Convert a CSV File to JSON
Problem:
Write a function that converts a CSV file into a JSON file.
import csv
import json
def csv_to_json(csv_filename: str, json_filename: str):
with open(csv_filename, mode="r") as csv_file:
data = list(csv.DictReader(csv_file))
with open(json_filename, mode="w") as json_file:
json.dump(data, json_file, indent=4)
# Example usage:
csv_to_json("data.csv", "data.json")
55. Send an Email using Python
Problem:
Write a function to send an email using Python’s smtplib
.
import smtplib
def send_email(sender_email: str, sender_password: str, recipient_email: str, subject: str, message: str):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(sender_email, sender_password)
email_body = f"Subject: {subject}\n\n{message}"
server.sendmail(sender_email, recipient_email, email_body)
server.quit()
print("Email sent successfully!")
# Example usage:
# Ensure to enable "Less Secure Apps" on your Gmail account before running
# send_email("your_email@gmail.com", "your_password", "receiver_email@gmail.com", "Test", "Hello!")
56. Web Scraping: Extract Titles from a Webpage
Problem:
Write a function that scrapes a webpage and extracts all titles (h1, h2, h3).
import requests
from bs4 import BeautifulSoup
def extract_titles(url: str):
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
titles = [tag.text.strip() for tag in soup.find_all(["h1", "h2", "h3"])]
return titles
# Example usage:
print(extract_titles("https://example.com"))
57. Find and Replace Text in a PDF
Problem:
Write a function that reads a PDF file, replaces a word, and saves a new PDF.
from PyPDF2 import PdfReader, PdfWriter
def replace_text_in_pdf(input_pdf: str, output_pdf: str, old_text: str, new_text: str):
reader = PdfReader(input_pdf)
writer = PdfWriter()
for page in reader.pages:
text = page.extract_text()
modified_text = text.replace(old_text, new_text)
writer.add_page(page)
writer.pages[-1].text = modified_text
with open(output_pdf, "wb") as output_file:
writer.write(output_file)
# Example usage:
# replace_text_in_pdf("input.pdf", "output.pdf", "old_word", "new_word")
58. Automate File Organization in a Folder
Problem:
Write a script that automatically organizes files in a folder into subfolders by file type.
import os
import shutil
def organize_files(directory: str):
if not os.path.exists(directory):
print("Directory not found!")
return
for file in os.listdir(directory):
file_path = os.path.join(directory, file)
if os.path.isfile(file_path):
ext = file.split(".")[-1]
ext_folder = os.path.join(directory, ext)
os.makedirs(ext_folder, exist_ok=True)
shutil.move(file_path, os.path.join(ext_folder, file))
# Example usage:
# organize_files("/path/to/your/folder")
59. Convert Text to Speech
Problem:
Write a Python script that converts text to speech using the pyttsx3
library.
import pyttsx3
def text_to_speech(text: str):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
# Example usage:
text_to_speech("Hello, this is Python speaking!")
60. Automate Screenshot Capture
Problem:
Write a script that captures a screenshot and saves it.
import pyautogui
def take_screenshot(filename: str):
screenshot = pyautogui.screenshot()
screenshot.save(filename)
# Example usage:
take_screenshot("screenshot.png")