DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 228

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: Unique Sum

Task

You are given an array of integers.

Write a script to find out the sum of unique elements in the given array.

My solution

This is relatively straight forward. This first thing I do is get the frequency of each number, and store it in the dict freq. The key is the input number and the value is the number of times it occurs.

for i in ints:
    freq[i] = 1 + freq.get(i, 0)
Enter fullscreen mode Exit fullscreen mode

The solution is going to be the sum of all keys in freq dict where the value is 1 (i.e. it only occurs once).

solution = sum(i for i in freq if freq[i] == 1)
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py 2 1 3 2
4

$ ./ch-1.py 1 1 1 1
0

$ ./ch-1.py 2 1 3 4
10
Enter fullscreen mode Exit fullscreen mode

Task 2: Empty Array

Task

You are given an array of integers in which all elements are unique.

Write a script to perform the following operations until the array is empty and return the total count of operations.

My solution

Some times I find it easier just to brute force a solution rather than trying to be clever. With the majority of these challenges we are talking about relatively small sets of data which is easy for any PC to compute.

And that is exactly how I approached this task. The first thing I do is get the current minimum value called min_int and set the moves variable to 0.

I have a loop that runs until the ints list is exhausted. For each iteration, I increment the moves value and remove the first item from the list. If the value is the current minimum, I calculate the new minimum. If it is not, I add it to the end of the list.

while len(ints):
    moves += 1
    value = ints.pop(0)

    if value == min_int:
        if len(ints):
            min_int = min(ints)
    else:
        ints.append(value)
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py 3 4 2
5

$ ./ch-2.py 1 2 3
3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)