DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 198

Two relatively straight forward tasks to start the new year.

Challenge, My solutions

Task 1: Max Gap

Task

You are given a list of integers, @list.

Write a script to find the total pairs in the sorted list where 2 consecutive elements has the max gap. If the list contains less then 2 elements then return 0.

My solution

For this task, I have defined two variables. The value gap records the largest gap between two numbers so far, while the count value records the number of occurrences of the gap.

The first thing I do is (numerically) sort the list. I then iterate from 0 to the size of the list minus two. For each iteration, I compare the difference in the value in that position to the one in the next position. If the gap is greater, I set gap to the difference, and reset count to 1. If the difference is the same as the current gap, I increase 1 to count.

Finally I display the value of count.

Examples

$ ./ch-1.py 2 5 8 1
2

$ ./ch-1.py 3
0
Enter fullscreen mode Exit fullscreen mode

Task 2: Prime Count

Task

You are given an integer $n > 0.

Write a script to print the count of primes less than $n.

My solution

Time to pull out my trusty is_prime method. This was last used in task 2 from challenge 177. I iterate from 1 to n-1 and added one to count if that number is a prime. Then I display the value of count.

Examples

$ ./ch-2.py 10
4

$ ./ch-2.py 15
6

$ ./ch-2.py 1
0

$ ./ch-2.py 25
9
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay