Skip to content
Advertisement

Python sum of number in array, ignoring sections of specific numbers

I am very new to Python and have been going through multiple tutorials to get better.

I have straggled with one difficult problem and found a solution. But it feels, works very newbie like. I think that I have tailored it to answer the specific question.

So the question is:

SUMMER OF ’69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.

JavaScript

My code to solve this is:

JavaScript

It is a very basic problem and I am very alerted that I have struggled with something like this already.

Advertisement

Answer

Short O(n) solution using an iterator and the in operator to search for (and thereby skip to) the 9 following each 6:

JavaScript

Less dense version:

JavaScript

Correctness check (random test cases) and benchmark (with [1] * 5000 + [6, 9] * 2500) along with the accepted answer’s solution (which takes O(n2)):

JavaScript

Code (Try it online!):

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement