In this part of the series, we continue exploring how to work with lists in Python without relying on built-in functions. These kinds of exercises are great for building strong problem-solving skills and a deeper understanding of data structures and algorithms.
Problem One: Count the Frequency of the Smallest Element
Task: You are given an array of integers. Write a function that returns the number of times the smallest element appears in the array.
Note: Do not usemin()
orcount()
. Try to solve this with a single list traversal.
Breakdown:
- If the list is empty, return
0
. - Initialize the smallest value with
float('inf')
and set a counter to0
. - Traverse the list:
- If the current number is smaller than the smallest, update the smallest and reset the counter to 1.
- If it's equal to the smallest, increment the counter.
def count_min(numbers):
if not numbers:
return 0
smallest = float('inf')
count = 0
for num in numbers:
if num < smallest:
smallest = num
count = 1
elif num == smallest:
count += 1
return count
Problem Two: Find the Second Largest Number
Task: You are given a list of integers. Write a function that returns the second-largest number.
If there are fewer than two unique numbers, returnNone
.
Breakdown:
- First, check if the list has at least two numbers. If not, return
None
. - Initialize
largest
andsecond_max
tofloat('-inf')
. - Loop through the numbers:
- If the number is greater than
largest
, updatesecond_max
tolargest
, then updatelargest
. - If the number is greater than
second_max
and not equal tolargest
, updatesecond_max
.
- If the number is greater than
- If
second_max
is still-inf
, returnNone
.
def second_max(nums):
if len(nums) < 2:
return None
largest = float('-inf')
second_max = float('-inf')
for num in nums:
if num > largest:
second_max = largest
largest = num
elif num > second_max and num != largest:
second_max = num
if second_max == float('-inf'):
return None
return second_max
Final Thoughts
Mastering these kinds of operations without relying on Python’s built-ins forces you to think like a computer and truly understand how things work under the hood. This knowledge becomes invaluable when working on more complex applications or preparing for coding interviews.
Top comments (0)