Weekly Challenge 306
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: Odd Sum
Task
You are given an array of positive integers, @ints
.
Write a script to return the sum of all possible odd-length sub-arrays of the given array. A sub-array is a contiguous sub-sequence of the array.
My solution
So I was starting to see if there was a pattern of how many times each number was counted. If we had 9 digits, they are counted 5, 8, 11, 12, 13, 12, 11, 8 and 5 times. As this didn't follow any easy pattern, I decided to do the task as described. Nothing wrong with that, computers have lots of CPU cycles available :)
For this task, I have two loops. The outer loop has the variable length
. It starts with 1 and increments by 2 until the length of the list (array in Perl). The inner loop has the variable start
to record the starting position of the sub-array. It starts with 0 (the first item in the ints
list) and ends with the length of the list minus the value of length
.
For each loop, I add the sum of the integers from start
to start + length - 1
to the solutions
value. I finish by returning the solutions
value.
def odd_sum(ints: list) -> int:
solution = 0
l = len(ints)
for length in range(1, l+1, 2):
for start in range(0, l-length+1):
solution += sum(ints[start:start+length])
return solution
Examples
$ ./ch-1.py 2 5 3 6 4
77
$ ./ch-1.py 1 3
4
Task 2: Last Element
Task
You are given a array of integers, @ints
.
Write a script to play a game where you pick two biggest integers in the given array, say x
and y
. Then do the following:
- if
x == y
then remove both from the given array - if
x != y
then removex
and replacey
with (y - x)
At the end of the game, there is at most one element left.
Return the last element if found otherwise return 0
.
My solution
This task is a little more straight forward, with Mohammad practically writing the code for us. While the number of items in the ints
list is greater than 1, I perform the following.
- Sort the list numerically, lowest first
- Remove the last item off the list, and assign it to
x
. - Remove the last item off the list, and assign it to
y
. - If
x
andy
are different, append the difference to theints
list.
Lastly I return the remaining value, or 0
if the list is empty.
def last_element(ints: list) -> int:
while len(ints) > 1:
ints.sort()
x = ints.pop()
y = ints.pop()
if x != y:
ints.append(x-y)
return ints[0] if ints else 0
Examples
$ ./ch-2.py 3 8 5 2 9 2
1
$ ./ch-2.py 3 2 5
0
Top comments (0)