DEV Community

Simon Green
Simon Green

Posted on

Counting and sorting

Weekly Challenge 238

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: Running Sum

Task

You are given an array of integers.

Write a script to return the running sum of the given array. The running sum can be calculated as sum[i] = num[0] + num[1] + … + num[i].

My solution

This is pretty straight forward. I have a variable total which keeps a running total. I then iterate over the list (array in Perl), and add the value to the solutions list.

for i in ints:
    total += i
    solution.append(total)

print('(' + ', '.join(map(str, solution)) + ')')
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py 1 2 3 4 5
(1, 3, 6, 10, 15)

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

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

Task 2: Persistence Sort

Task

You are given an array of positive integers.

Write a script to sort the given array in increasing order with respect to the count of steps required to obtain a single-digit number by multiplying its digits recursively for each array element. If any two numbers have the same count of steps, then print the smaller number first.

My solution

This is very similar to the second challenge in week 233.

The first step is calculate the steps required to convert the number to a single digit. I store this in the steps dict (hash in Perl).

for i in ints:
    steps[i] = 0
    num = abs(i)
    while len(str(num)) > 1:
        num = prod(map(int, str(num)))
        steps[i] += 1
Enter fullscreen mode Exit fullscreen mode


`

In Python, sorting is stable. This means if two things are equal the original order is preserved.

I sort the list twice. The first sort is numerically, and then the steps of the number.

python
sorted_ints = sorted(ints)
sorted_ints = sorted(sorted_ints, key=lambda i: steps[i])

The Perl code is very similar. The main difference is that I do the sort in a single operation.

perl
my @sorted_ints = sort { $steps{$a} <=> $steps{$b} || $a <=> $b } @ints;

Examples

`bash
$ ./ch-2.py 15 99 1 34
(1, 15, 34, 99)

$ ./ch-2.py 50 25 33 22
(22, 33, 50, 25)
`

Top comments (0)