Weekly Challenge

WBOY
Release: 2024-08-27 06:05:32
Original
861 people have browsed it

Weekly Challenge

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')
Copy after login

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
Copy after login

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




</p>
<h3>
  
  
  Examples
</h3>



<pre class="brush:php;toolbar:false">$ ./ch-2.py 1 2 1 0
true

$ ./ch-2.py 0 3 0
false
Copy after login

The above is the detailed content of Weekly Challenge. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template