Weekly Challenge 263
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: Target Index
Task
You are given an array of integers, @ints
and a target element $k
.
Write a script to return the list of indices in the sorted array where the element is same as the given target element.
My solution
This is a pretty straight forward task, so doesn't require much explanation. I sort the array (numerically), and then return the index of items that equally k
in the list.
def target_index(ints: list, k: int) -> list:
ints = sorted(ints)
return [pos for pos, value in enumerate(ints) if value == k]
Examples
$ ./ch-1.py 1 5 3 2 4 2 2
(1, 2)
$ ./ch-1.py 1 2 4 3 5 6
()
$ ./ch-1.py 5 3 2 4 2 1 4
(4)
Task 2: Merge Items
Task
You are given two 2-D array of positive integers, $items1
and $items2
where element is pair of (item_id, item_quantity).
Write a script to return the merged items.
My solution
My solution to this task is broken into two chunks. The first is to calculate the cumulative totals for each item. While the task mentioned items1
and items2
as variables, I've use the more meaningful variables item_id
and item_qty
.
from collections import defaultdict
def merge_items(*arrays) -> list:
# Calculate the total of each items
totals = defaultdict(int)
for array in arrays:
for item in array:
item_id, item_qty = item
totals[item_id] += item_qty
The second part of the task is turning the dict (hash in Perl) into a list of item_id
and item_qty
pairs. This can be done in a single line with list comprehension.
return [[item, totals[item]] for item in sorted(totals)]
Examples
$ ./ch-2.py "[ [1,1], [2,1], [3,2] ]" "[ [2,2], [1,3] ]"
[[1, 4], [2, 3], [3, 2]]
$ ./ch-2.py "[ [1,2], [2,3], [1,3], [3,2] ]" "[ [3,1], [1,3] ]"
[[1, 8], [2, 3], [3, 3]]
$ ./ch-2.py "[ [1,1], [2,2], [3,3] ]" "[ [2,3], [2,4] ]"
[[1, 1], [2, 9], [3, 3]]
Top comments (0)