While working through the CodingBat exercises today, I came across the following challenge:

Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.

array123([1, 1, 2, 3, 1]) → True

array123([1, 1, 2, 4, 1]) → False

array123([1, 1, 2, 1, 2, 3]) → True

I personally challenged myself to refactor my solutions into one line of code, which is forcing me to look into some more advanced Python methods. Here’s my solution:

But first, take a look at the official CodeBat solution:

def array123(nums): # Note: iterate with length-2, so can use i+1 and i+2 in the loop for i in range(len(nums)-2): if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3: return True return False

Not too bad, but it’s still seems more complicated than it needs to be.

After searching around for a better way, I stumbled upon this StackOverflow question.

Inspired by the first answer, I came up with the following solution:

def array123(nums): return set([1,2,3]) & set(nums) == set([1,2,3])

A set of list is a list of unique values in that list. For example, try this in your command line:

$ python >>> arr = [1,1,2,2,4] >>> set(arr) set([1,2,4]) >>> arr2 = [1,2,2] >>> set(arr2) set([1,2]) >>> set(arr) & set(arr2) set([1,2])

Check out more on sets here. They definitely look useful for working with two sets of lists!

Python sets are totally sweet, also there’s this neat syntax for them:

set([1,2,3]) == {1,2,3}

Sadly, sets are unordered. If I understand the original question correctly, they want to find the ordered sequence [1,2,3] in the array, which sets will not do. Compare with the input [3, 1, 2, 1, 2, 2].

However! It’s definitely possible to do it in one line, but I only came up with this longish list comprehension, which is a bit hard to read:

array123 = lambda x: any([1,2,3] == x[offset:offset+3] for offset in range(len(x)))

If you’re going for hilarity, though, try this one:

array123 = lambda x: ‘, 1, 2, 3,’ in str([0] + x + [0])

Thanks Chris! This is super useful. Love the simplified syntax {1,2,3} and your overly complicated solutions 🙂

I think I’ll write a blog post looking more deeply into these to make sure I understand. Super cool.