:3
Everything is barely weeks. Everything is days. We have minutes to live.
- about me
- Github: @r1bb1t-h0l3
Everything is barely weeks. Everything is days. We have minutes to live.
Posted
Reversing a list is a common operation, especially in algorithmic problem-solving and data manipulation. Even though Python provides simple, built-in ways to reverse a list, since I am specifically trying to improve my algorithmic thinking and logical reasoning skills, I am focussing on purely algorithmic reversal. Specifically I am doing this as prep to solving a DMOJ problem I am working on which I will share a bit later.
So here are the three different ways I found to reverse a list in Python without using any built-in methods like .reverse()
or slicing([::-1])
. They all make sense to me, so hopefully as I get a little more practise implementing them the logic will start to feel second nature. My favourite is the last one with modulo and floor division, as the second one still feels a bit like “python magic” with tuple unpacking being used.
One of the simplest ways to reverse a list is to build a new list by iterating over the original list from the end to the beginning. This approach is straightforward and doesn’t modify the original list.
# Original list
numbers = [1, 2, 3, 4, 5]
# Create an empty list to hold the reversed elements
reversed_numbers = []
# Iterate from the end of the original list to the beginning
for i in range(len(numbers) - 1, -1, -1):
reversed_numbers.append(numbers[i])
print(reversed_numbers) # Output: [5, 4, 3, 2, 1]
How It Works:
We use a loop to move from the last element(len(numbers) - 1)
down to the first (0)
.
Each element is appended to the reversed_numbers list, building the reversed list step-by-step.
Pros and Cons:
Pros: This approach doesn’t modify the original list, which can be useful if you need to keep the original data intact. Cons: It requires additional space (a new list), which can be inefficient for very large lists.Use Case: Use this method when you need a reversed copy of the list, leaving the original list unmodified.
If you want to reverse the list in place (modifying the original list) without using additional memory, a two-pointer technique is highly efficient. This method involves swapping elements from the two ends of the list, gradually moving toward the center. I do like the two-pointer approach as well.
Code Example:
# Original list
numbers = [1, 2, 3, 4, 5]
# Initialize pointers
start = 0
end = len(numbers) - 1
# Swap elements until the pointers meet in the middle
while start < end:
# Swap elements at start and end
numbers[start], numbers[end] = numbers[end], numbers[start]
# Move pointers toward the center
start += 1
end -= 1
print(numbers) # Output: [5, 4, 3, 2, 1]
How It Works:
We start with two pointers:start
at the beginning and end
at the end of the list.
Each iteration swaps the elements at start
and end
, then moves both pointers inward until they meet in the middle.
Pros and Cons:
Pros: This approach doesn’t require extra space, making it memory efficient. Cons: It modifies the original list, so it’s not suitable if you need the original order preserved.Use Case: Use this method when you want an in-place reversal of the list to save memory, especially with large lists.
When reversing a list of digits stored as an integer (like 12345), it’s possible to reverse it manually without converting it to a string. This method is useful when working with numbers directly.
Code Example:
# Original number
num = 12345
reversed_num = 0
while num > 0:
# Extract the last digit
last_digit = num % 10
# Shift reversed_num left and add the last digit
reversed_num = reversed_num * 10 + last_digit
# Remove the last digit from num
num //= 10
print(reversed_num) # Output: 54321
How It Works:
We extract the last digit fromnum
using modulo (num % 10)
.
We multiply reversed_num
by 10 (shifting digits left) and add the extracted digit.
We divide num
by 10 (integer division) to remove the last digit.
This process continues until num
becomes 0.
Pros and Cons:
Pros: This method works entirely on integers, so there’s no need to convert between types. Cons: Limited to numbers; won’t work with lists of other types.Use Case: Use this method when working with integers where you need to reverse the digits.
So as far as I can surmise these are the three main algorithmic methods to reverse a number list in place. For my purposes only methods 1 and 2 are valid because I need to reverse a string of letters. I will post the challenge I am working on next!
Posted
In Python a set is considered to be an unordered collection of unique elements. I found out about this method when solving the From 1967 to 2013 Problem on DMOJ. I actually wrote a different solution initially, one that iterated through 4 digits, comparing them to each other, but then I noticed that the input can go up to the tens of thousands. Also my submission only passed half the test cases😩.
I knew I needed a better way so I started researching and found the set()
method. A set can be made from any iterable like a list, string or tuple and removes any duplicate values, which was perfect for this task.
I do feel like using set()
is almost cheating here, as I generally avoid using “Python magic” to solve challenges, but this solution just looks so elegant. Anyways, here it is:
# 56 From 1987 to 2013 ccc13s1
def digit_same(year) -> bool:
return len(set(year)) != len(year)
input_year = int(input())
year = str(input_year + 1)
while digit_same(year):
num_year = int(year)
num_year += 1
year = str(num_year)
print(year)
Author
ribbit
Categories
coding challenge
Posted
To further my understanding of the Bootstrap framework, I decided to create a one-page portfolio. The idea behind the design was to have each section fill the screen as you navigate through it. So, when you switch between sections, the viewfinder shifts smoothly, giving a full-screen focus to each part. However, when you scroll down normally, there’s quite a bit of blank space, which I’m not totally sure I like. But, on the flip side, I really like the clean, minimalist look it gives, so I’m leaving it for now. Maybe I’ll come up with a way to refine it down the line.
Starting at the top, the main section showcases basic portfolio information. This is intended for a web design portfolio, though, for now, it’s just filled with placeholder text. Scrolling down, you’ll find a metrics section with social media links and a few skill graphs. I know skill graphs are controversial—honestly, I’m not a huge fan of them either—but I wanted to experiment with Bootstrap’s potential, so I included them here.
At the bottom, there’s a portfolio section where you can upload your own work samples, followed by a footer. The design overall is simple, but it leverages Bootstrap’s features well. It’s clean, straightforward, and serves as a decent portfolio template, especially for a beginner project.
You can see the page here (if you missed it linked at the top 😛)
Posted
Over the past month, I’ve been focusing on improving my fundamental programming skills, not by learning more Python tricks, but by strengthening my core understanding of programming concepts. A lot of this has involved working on DMOJ problems and reading Learn to Code by Solving Problems by Daniel Zingaro.
Recently, while solving a problem from the Timus judge, the book introduced the top-down approach. This approach has been incredibly helpful for me, especially when it comes to structuring code and using functions effectively. The top-down method encourages you to start by breaking down a task into broad steps and then narrowing down what each function needs to accomplish.
I’ve often struggled with organizing tasks in code, particularly when it comes to breaking down a complex problem into manageable steps. The top-down approach provides a clear way to do this. By writing commentary for each function, you not only clarify what the function does but also ensure your code is easier to understand and maintain.
Below is an example from the Timus judge Action figures problem, using the top-down approach with helpful comments. This method helped me write clearer, more concise programs, and I found it valuable in organizing my thoughts around function-based programming.
#Read input
#Check whether all boxes are OK
#Obtain a new lit of boxees with only left and right heights
#Sort boxes
#Determine whether boxes are organised
def read_boxes(n):
"""
n is the number of boxes to read.
Read the boxes from the input, and return them as a list of boxes;
Each box is a list of action figure heights.
"""
boxes = []
for i in range(n):
box = input().split()
box.pop(0)
for i in range(len(box)):
box[i] = int(box[i])
boxes.append(box)
return boxes
def all_boxes_ok(boxes):
"""
boxes is a list of boxes; each box is a list of action figure heights.
Return True if each box in boxes has its action figures in
nondecreasing order of height, False otherwise.
"""
for box in boxes:
if not box_ok(box):
return False
return True
def box_ok(box):
"""
box is the list of action figure heights in a given box.
Return True if the heights in box are in nondecreasing order,
False otherwise.
"""
for i in range(len(box) - 1):
if box[i] > box[i + 1]:
return False
return True
def boxes_endpoints(boxes):
"""
boxes is a list of boxes; each box is a lit of action figure heights.
return a list, where each value is a list of two values:
the heights of the leftmost and rightmost figures in a box.
"""
endpoints = []
for box in boxes:
endpoints.append(box[0], box[-1])
return endpoints
def all_endpoints_ok(endpoints):
"""
endpoints is a list, where each value is a list of two values:
the heights of the leftmost and rightmost action figures in a box.
Requires: endponts is sorted by action figure heights.
Return True if the endpoints came from boxes that can be put in order,
False otherwise.
"""
maximum = endpoints[0][1]
for i in range(1, len(endpoints)):
if endpoints[i][0] < maximum:
return False
maximum = endpoints[i][1]
return True
#Main Program
#Read input
n = int(input())
boxes = read_boxes(n)
#Check whether all boxes are OK
if not all_boxes_ok(boxes):
print('NO')
else:
#Obtain a new list of boxes with only left and ight heights
endpoints = boxes_endpoints(boxes)
#Sort boxes
endpoints.sort()
#Determine whether boxes are organised
if all_endpoints_ok(endpoints):
print('YES')
else:
print('NO')
Author
ribbit
Categories
coding challenge
Posted
As part of my journey into front-end development, I decided to learn Bootstrap after spending some time with CSS and Flexbox. Bootstrap is often recommended as an easy-to-learn framework for beginners, and that’s what drew me to it. After using it for a few weeks, I found the framework — and especially the documentation — simple, clear, and incredibly helpful. Although I’m still scratching the surface, my overall experience has been positive, and I can see the vast potential Bootstrap offers for building responsive websites. I used Bootstrap 5 for this, as I figured that I might ass well learn the newest one.
One of the things I appreciate most about Bootstrap is its ease of use. It simplifies complex tasks, such as working with Flexbox, by providing easy-to-implement classes. Vanilla Flexbox can be tricky, but Bootstrap makes it accessible with minimal effort.
Another benefit is how quickly you can add functional elements like a hamburger menu or dropdowns. These would take much more time and effort to code from scratch using only HTML and CSS. Bootstrap’s built-in components save time and simplify the process of adding interactive features.
That said, there are a few things I find limiting. Bootstrap has a very opinionated style, which means websites built with it often look similar. While customization options are available, fully breaking away from the default Bootstrap aesthetic can be difficult.
Another challenge I faced was integrating Bootstrap into an existing vanilla CSS and HTML site. Bootstrap’s styles tend to override custom styles, and getting them to coexist can be tricky. The pre-defined styles are powerful, but sometimes you end up fighting them to achieve your original design.
Despite the challenges, I enjoyed working with Bootstrap to create a blog template. It incorporates several Bootstrap elements, such as headings, a hamburger menu, and cards for blog posts. The process was fun, and it gave me a chance to explore more of what Bootstrap has to offer.
In summary, Bootstrap has proven to be a helpful tool for building responsive layouts quickly, but like any framework, it comes with its own set of challenges.
P.S. Please excuse the ridiculous dummy text. I had entirely too much time adding fun quotes as content.
The template can be seen here: Blog template
Author
ribbit
Categories
personal project