In today’s blog, we’ll walk through three common list operations that are often solved using Python’s built-in methods—but this time, we’ll solve them from scratch. This approach is especially useful for improving your algorithmic thinking and mastering the fundamentals.
Problem One: Reverse a List
You are given a list of
n
integers. Your task is to return a reversed list, without using any built-in Python functions or methods related to reversing.
Breakdown
- Initialize an empty list to store the reversed elements.
- Iterate over the original list in reverse order using index manipulation.
- Append each element to the new list.
- Return the new list.
def reverse_list(numbers):
reversed_list = []
for i in range(len(numbers) - 1, -1, -1):
reversed_list.append(numbers[i])
return reversed_list
Problem Two: Circular Shift Elements
Given a list of
n
integers and an integershift
, return the list after shifting each element right (positive shift) or left (negative shift), circularly.
Breakdown
- Normalize the shift using
shift = shift % n
to keep it within bounds. - Initialize a new list with the same length.
- Loop through the original list and compute the new index using
(i + shift) % n
. - Assign the value from the old list to its new position in the new list.
- Return the shifted list.
def shift_list_elements(ls, shift):
n = len(ls)
if n == 0:
return []
shift = shift % n
shifted_list = [0] * n
for i in range(n):
new_pos = (i + shift) % n
shifted_list[new_pos] = ls[i]
return shifted_list
Problem Three: Check for Contiguous Sublist
You are given two lists of integers,
listA
andlistB
. Determine iflistB
is a contiguous sublist oflistA
.
Breakdown
- If
listB
is longer thanlistA
, returnFalse
. - Loop through
listA
, only up to wherelistB
can possibly fit. - For each start index, check if every element in
listB
matches the corresponding elements inlistA
. - Return
True
if a full match is found; otherwise, returnFalse
.
def is_contiguous_sublist(listA, listB):
lenA = len(listA)
lenB = len(listB)
if lenB > lenA:
return False
for i in range(lenA - lenB + 1):
match_found = True
for j in range(lenB):
if listA[i + j] != listB[j]:
match_found = False
break
if match_found:
return True
return False
Each of these problems helps reinforce core concepts in indexing, iteration, and logic building, without depending on Python's built-ins. Try them out and consider how you might further optimize these for large datasets or edge cases!