Weekly Challenge 345
Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.
Task 1: Peak Positions
Task
You are given an array of integers, @ints.
Find all the peaks in the array, a peak is an element that is strictly greater than its left and right neighbours. Return the indices of all such peak positions.
My solution
This is relatively straight forward. I start by comparing the first two elements and add 0 to the peaks list (array in Perl) if the first value is higher.
I then compare the middle values, adding the position to the peaks list if it's before and after values are lower. Finally I compare the last two values.
def peak_positions(ints: list[int]) -> list[int]:
peaks = []
if ints[0] > ints[1]:
peaks.append(0)
for pos in range(1, len(ints) - 1):
if ints[pos] > ints[pos - 1] and ints[pos] > ints[pos + 1]:
peaks.append(pos)
if ints[-1] > ints[-2]:
peaks.append(len(ints) - 1)
return peaks
Examples
$ ./ch-1.py 1 3 2
(1)
$ ./ch-1.py 2 4 6 5 3
(2)
$ ./ch-1.py 1 2 3 2 4 1
(2, 4)
$ ./ch-1.py 5 3 1
(0)
$ ./ch-1.py 1 5 1 5 1 5 1
(1, 3, 5)
Task 2: Last Visitor
Task
You are given an integer array @ints where each element is either a positive integer or -1.
We process the array from left to right while maintaining two lists:
-
@seenstores previously seen positive integers (newest at the front) -
@ansstores the answers for each -1
Rules:
- If
$ints[i]is a positive number -> insert it at the front of@seen - If
$ints[i]is -1:- Let
$xbe how many-1s in a row we’ve seen before this one. - If
$x < len(@seen)-> appendseen[x]to@ans - Else -> append -1 to
@ans
- Let
At the end, return @ans.
My solution
I actually don't understand this task. However, I've followed the instructions in the task, and get the expected results. I renamed x as neg_count to make it more meaningful.
def last_visitor(ints: list[int]) -> list[int]:
seen = []
ans = []
neg_count = 0
for i in ints:
if i > 0:
seen.insert(0, i)
neg_count = 0
elif i == -1:
if neg_count < len(seen):
ans.append(seen[neg_count])
else:
ans.append(-1)
neg_count += 1
else:
raise ValueError("Input integers must be positive or -1.")
return ans
Examples
$ ./ch-2.py 5 -1 -1
(5, -1)
$ ./ch-2.py 3 7 -1 -1 -1
(7, 3, -1)
$ ./ch-2.py 2 -1 4 -1 -1
(2, 4, 2)
$ ./ch-2.py 10 20 -1 30 -1 -1
(20, 30, 20)
$ ./ch-2.py -1 -1 5 -1
(-1, -1, 5)
Top comments (0)