DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 139

Challenge, My Solutions

Now with Python

Before I get stuck into my solutions for this task, I have some news. I've used Perl for over 20 years, and think I'm pretty good at it. However, Python is something relatively new for me. I've only really used it for the past five years, and I'm using it more and more at work these days. So from this week forward, I'll do at least one solution in Python. On with that, here's this weeks blog.

TASK #1 › JortSort


You are given a list of numbers.

Write a script to implement JortSort. It should return true/false depending if the given list of numbers are already sorted.

My solutions

This is relatively straight forward and my solutions in both languages follow the same logic.

  • Assume the numbers are sorted
  • Iterate through the array (Perl) / list (Python) from the second element to the last. If that value is smaller than the previous one, we know it is not sorted, and can exit the iterations early.
  • Display 0 or 1 (representing false or true)

The main difference between the Perl and Python code is that Python doesn't automatically convert strings to numbers, so that has to be done manually.


$ ./ 1 2 3 4 5

$ ./ 1 3 2 4 5
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Long Primes


Write a script to generate first 5 Long Primes. A prime number (p) is called Long Prime if (1/p) has an infinite decimal expansion repeating every (p-1) digits.

My solution

Like with the first solution, my solutions this task follow the same methodology for both languages. I start from three and keep counting until I find five numbers that (a) are primes and (b) has an infinite decimal expansion repeating every n-1 digits.

To determine if a number is a prime, I have a function that counts from 2 to the square root of the number. If the number is divisible by that value without a remainder, I return false. If the loop ends, then I return true.

To determine the second conditional, we can be use the logic of the repeating decimals formula to calculate the number of digits required to repeat the sequence. This was also used in the second task of challenge 106.

Unlike that time, we aren't really interested in the actual digits. For this this task, I take the value of (10 * remainder) mod number and keep looping until we hit the same remainder.

Then it's a matter of printing the list. For Perl that is say join ', ', @solutions while Python is print(*solutions, sep=', ').


$ ./ 
7, 17, 19, 23, 29

$ ./ 
7, 17, 19, 23, 29
Enter fullscreen mode Exit fullscreen mode

Top comments (0)