DEV Community

Simon Green
Simon Green

Posted on

Finding the target

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.

Challenge, My solutions

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]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)]
Enter fullscreen mode Exit fullscreen mode

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]]

Enter fullscreen mode Exit fullscreen mode

Top comments (0)