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.
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)
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
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
- The numeric representation of the string in base 10 if it is made up of digits only.
- 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)
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)))
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 );
}
Examples
$ ./ch-2.py perl 2 000 python r4ku
6
$ ./ch-2.py 001 1 000 0001
1
Top comments (0)