DEV Community

Simon Green
Simon Green

Posted on

The greatest array

Weekly Challenge 264

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: Greatest English Letter

Task

You are given a string, $str, made up of only alphabetic characters [a..zA..Z].

Write a script to return the greatest English letter in the given string.

A letter is greatest if it occurs as lower and upper case. Also letter b is greater than a if b appears after a in the English alphabet.

My solution

For this challenge, I work backwards from z to a and return the first letter that appears in both cases. If str was going to be very long, it would be faster to convert this to a set (hash in Perl) for faster lookup. However this is definitely not needed for a small string.

def greatest_letter(s: str) -> str | None:
    for letter in string.ascii_uppercase[::-1]:
        if letter in s and letter.lower() in s:
            return letter

    return None
Enter fullscreen mode Exit fullscreen mode

Examples

 ./ch-1.py PeRlwEeKLy
L

$ ./ch-1.py ChaLlenge
L

$ ./ch-1.py The
''
Enter fullscreen mode Exit fullscreen mode

Task 2: Target Array

Task

You are given two arrays of integers, @source and @indices. The @indices can only contains integers 0 <= i < size of @source.

Write a script to create target array by insert at index $indices[i] the value $source[i].

My solution

One thing the challenge does not specify is what happens if the value of indices is outside the current length of the of the solution. Python's insert and Perl's splice will append the value to the end of the array (without padding), so I'm following that for this task. It would be trivial to raise an exception if that was the desired behavior.

With that in mind, the task is pretty straight forward. I create an empty list (array in Perl) called solution. I then iterate through the two lists, adding the value in the source list at the position in the indices list.

def target_array(source: list, indices: list) -> list:
    solution = []
    for i in range(len(source)):
        solution.insert(indices[i], source[i])

    return solution
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py "(0, 1, 2, 3, 4)" "(0, 1, 2, 2, 1)"
(0, 4, 1, 3, 2)

$ ./ch-2.py "(1, 2, 3, 4, 0)" "(0, 1, 2, 3, 0)"
(0, 1, 2, 3, 4)

$ ./ch-2.py "(1)" "(0)"
(1)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)