DEV Community

Simon Green
Simon Green

Posted on

Small and large

Weekly Challenge 250

Sorry for no blog post last week. I acquired the 'rona for the second time, and it knocked me for six. Feeling better this week.

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: Smallest Index

Task

You are given an array of integers, @ints.

Write a script to find the smallest index i such that i mod 10 == $ints[i] otherwise return -1.

My solution

This is relatively straight forward. Set the solutions variable to -1. Iterate through each array position. Set the solution variable and exit the loop if the condition is true.

solution = -1

for idx in range(len(ints)):
    if idx % 10 == ints[idx]:
        solution = idx
        break

print(solution)
Enter fullscreen mode Exit fullscreen mode

Examples

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

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

$ ./ch-1.py 1 2 3 4 5 6 7 8 9 0
-1
Enter fullscreen mode Exit fullscreen mode

Task 2: Alphanumeric String Value

Task

You are given an array of alphanumeric strings.

Write a script to return the maximum value of alphanumeric string in the given array.

The value of alphanumeric string can be defined as

  1. The numeric representation of the string in base 10 if it is made up of digits only.
  2. otherwise the length of the string

My solution

For this task, I create a function called calculate_value. Given a value it will return the integer representation if it looks like a non-negative value, otherwise it returns the length of the string

def calculate_value(s):
    return int(s) if re.search(r'^\d+$', s) else len(s)
Enter fullscreen mode Exit fullscreen mode

For the main function, I use a combination of the max and map functions to obtain the maximum value.

print(max(map(calculate_value, values)))
Enter fullscreen mode Exit fullscreen mode

The Perl code follows the same logic, although the syntax is slightly different. The max function comes from the List::Util module

sub calculate_value ($s) {
    return $s =~ /^[0-9]+$/ ? int($s) : length($s);
}

sub main (@values) {
    say max( map { calculate_value($_) } @values );
}
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py perl 2 000 python r4ku
6

$ ./ch-2.py 001 1 000 0001
1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)