DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 231

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: Min Max

Task

You are given an array of distinct integers.

Write a script to find all elements that is neither minimum nor maximum. Return -1 if you can’t.

My solution

This should be relatively straight forward. The first step is to calculate the minimum and maximum integers are store them as min_int and max_int.

After this, I retrieve the integers that aren't the maximum or minimum. I also convert them to strings so they can be joined.

solution = [str(i) for i in ints if i != min_int and i != max_int]
Enter fullscreen mode Exit fullscreen mode

Finally I print the print the results depending if any integers were found.

if len(solution):
    print('(' + ', '.join(solution) + ')')
else:
    print('-1')
Enter fullscreen mode Exit fullscreen mode

Examples

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

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

$ ./ch-1.py 2 1 3
(2)
Enter fullscreen mode Exit fullscreen mode

Task 2: Senior Citizens

Task

You are given a list of passenger details in the form “9999999999A1122”, where 9 denotes the phone number, A the sex, 1 the age and 2 the seat number.

Write a script to return the count of all senior citizens (age >= 60).

My solution

This is a really bad format for storing the data. Phone numbers can be of varying length (at least in Australia and New Zealand), people can be over 99 years old, and there could be more than 100 or more seats. I'll just ignore those issues for this task :)

For this task, I count the number of items in the list where the fourth and third last digits are greater than or equal to sixty.

In Python the code is

count = sum(1 for p in passengers if int(p[-4:-2]) >= 60)
Enter fullscreen mode Exit fullscreen mode

In Perl, we know that if we ask for a scalar from any array, we will get the number of elements. This means I can simply use the grep function to count the matching rows

my $count = grep { substr( $_, -4, 2 ) >= 60 } @passengers;
Enter fullscreen mode Exit fullscreen mode

Examples

 ./ch-2.py 7868190130M7522 5303914400F9211 9273338290F4010
2

$ ./ch-2.py 1313579440F2036 2921522980M5644
0
Enter fullscreen mode Exit fullscreen mode

Top comments (0)