Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This probably won't win any efficiency awards, but you get style points for the list comprehensions.</p> <p>This is how I would approach the problem. Make a list of a sliding window of size 3.</p> <pre><code>&gt;&gt;&gt; nums = [1, 3, 5, 6, 7, 8, 9, 10, 15, 19, 20, 22, 23, 24, 26, 27, 28, 32, 33, 35, 37, 38, 39, 40, 41, 42, 43, 44, 47, 48] &gt;&gt;&gt; [nums[i:i+3] for i in xrange(len(nums))] [[1, 3, 5], [3, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10, 15], [10, 15, 19], [15, 19, 20], [19, 20, 22], [20, 22, 23], [22, 23, 24], [23, 24, 26], [24, 26, 27], [26, 27, 28], [27, 28, 32], [28, 32, 33], [32, 33, 35], [33, 35, 37], [35, 37, 38], [37, 38, 39], [38, 39, 40], [39, 40, 41], [40, 41, 42], [41, 42, 43], [42, 43, 44], [43, 44, 47], [44, 47, 48], [47, 48], [48]] </code></pre> <p>Next step, get rid of the consecutive items, which is trivially easy now. This predicate will get cleverly filter out the consecutive items.</p> <pre><code>&gt;&gt;&gt; [nums[i] for i in xrange(len(nums)) if nums[i:i+3] != range(nums[i],nums[i]+3)] [1, 3, 9, 10, 15, 19, 20, 23, 24, 27, 28, 32, 33, 35, 43, 44, 47, 48] </code></pre> <p>EDIT:</p> <p>Eric brought up a good point, the solution above does not work entirely. If you want this to work, then predicate is going to need some beefing up. First, I derived these equations. They perform the windowing operation. Convince yourself that they are true:</p> <pre><code>a = [1,2,3,4,5] i = 2 a[i-0:i+3] == range(a[i-0], a[i]+3) # left a[i-1:i+2] == range(a[i-1], a[i]+2) # center a[i-2:i+1] == range(a[i-2], a[i]+1) # right </code></pre> <p>Then you <em>could</em> jam it in there sideways...</p> <pre><code>[a for i,a in enumerate(nums) if all(nums[i-j:i+k] != range(nums[i-j], nums[i]+k) for j,k in zip(xrange(0,3,1), xrange(3,0,-1)))] </code></pre> <p>But if you don't want to get shot, pull out the predicate into a function:</p> <pre><code>consec_to_buddies = lambda i, xs: ( xs[i-0:i+3] == range(xs[i-0], xs[i]+3) or xs[i-1:i+2] == range(xs[i-1], xs[i]+2) or xs[i-2:i+1] == range(xs[i-2], xs[i]+1) ) [a for i,a in enumerate(nums) if not consec_to_buddies(i, nums)] </code></pre> <p>Again, this isn't the most efficient, as you will be calculating the predicate for every item, even if you already know you are taking it out. The price you pay for elegance :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload