DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 283

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 Number

Task

You are given an array of integers, @ints, where every elements appears more than once except one element.

Write a script to find the one element that appears exactly one time.

My solution

Both of this weeks challenges involves the frequency of integers. Python has the Counter function (from the collections module) that automatically converts a list of things into dict of frequencies. For the Perl solution, I do this by hand.

Once I have the freq dict populated, I then find all integers that only appear once using list comprehension. This is stored in the variable once_only. If there is one value in the list, I return it. Otherwise I will raise an appropriate error message.

def unique_number(ints: list) -> int:
    freq = Counter(ints)
    only_once = [i for i in freq if freq[i] == 1]

    if len(only_once) == 1:
        return only_once[0]

    if len(only_once) == 0:
        raise ValueError('No values only appear once')

    raise ValueError('More than one value appears once')
Enter fullscreen mode Exit fullscreen mode

Examples

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

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

$ ./ch-1.py 1
1

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

Task 2: Digit Count Value

Task

You are given an array of positive integers, @ints.

Write a script to return true if for every index i in the range 0 <= i < size of array, the digit i occurs exactly the $ints[$i] times in the given array otherwise return false.

My solution

Like with the last task, I create dict (hash in Perl) called freq to store the frequency of each integer. I then word through the list to check that the condition is meet with each value.

def digit_count_value(ints: list) -> bool:
    freq = Counter(ints)

    for idx, value in enumerate(ints):
        if freq[idx] != value:
            return False

    return True
Enter fullscreen mode Exit fullscreen mode

Examples

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

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

Top comments (0)