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!