Skip to content Skip to sidebar Skip to footer

Looking For A More Elegant Solution To This

Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0

Solution 1:

If we can just remove the elements that we don't want, then we can use a simple sum. Here is an example:

defsum67(nums):
    nums=nums[:]
    while6in nums:
        i=nums.index(6)
        j=nums.index(7,i)
        del nums[i:j+1]
    returnsum(nums)

First, we use nums=nums[:] to make a copy. The caller probably isn't expecting nums to change.

nums.index(6) finds the index of the first element that has a value of 6. nums.index(7,i) finds the index of the first element that has a value of 7 after the index i. del nums[i:j+1] then deletes the elements in the range from i to j, including the element at j.

Solution 2:

The thing I like most about Python is that it makes it so easy to break a problem apart.

defskip67(seq):
    skipping = Falsefor value in seq:
        skipping = skipping or value == 6yield0if skipping else value
        skipping = skipping and value != 7defsum67(seq):
    returnsum(skip67(seq))

>>> sum67([1, 2, 2])
5>>> sum67([1, 2, 2, 6, 99, 99, 7])
5>>> sum67([1, 1, 6, 7, 2])
4

Solution 3:

This isn't too bad (you might argue it's trying to be too clever though).

>>>defsum67(nums):...while6in nums:...        index = nums.index(6)...while nums.pop(index) != 7:...pass...returnsum(nums)...>>>sum67([1, 2, 3])
6
>>>sum67([1, 2, 2, 6, 99, 99, 7])
5
>>>sum67([1, 1, 6, 7, 2])
4
>>>sum67([1, 2, 2, 6, 99, 99, 7, 8, 1, 6, 0, -1000, 7, 2])
16

Here's a really goofy one(will not work with negative numbers)

>>>import re>>>defsum67(nums):...returnsum(int(j) for j in re.sub(r'6\d*?7', '', ''.join((str(i) for i in nums))))>>>sum67([1, 2, 3])
6
>>>sum67([1, 2, 2, 6, 99, 99, 7])
5
>>>sum67([1, 2, 2, 6, 99, 99, 7, 8, 1, 6, 0, 7, 2])
16

Please don't ever write code like that :p

One more awful one liner before I leave this alone:

>>>defsum67(nums):...returnsum(i if i != 6else -sum(nums[pos+1:nums.index(7,pos)+1]) for pos, i inenumerate(nums))...>>>sum67([1, 2, 2, 6, 99, 99, 7])
5
>>>sum67([1, 2, 2, 6, 99, 99, 7, 8, 1, 6, 0, -1000, 7, 2])
16

Solution 4:

defsum67(nums):
  i=0sum=0
  n=len(nums)
  while i<n:
    if nums[i]==6:
      i=nums.index(7,i)
    else:
      sum += nums[i]
    i+=1returnsum

Solution 5:

defsum67(L):
    it = iter(L)
    returnsum(all(i!=7for i in it) if i == 6else i for i in it)

A slightly more readable version if you're interested in how this works:

defslice67(L):
    it = iter(L)

    for i in it:
        if i != 6:
            yield i
        else:
            whilenext(it, 7) != 7:
                passprintsum(slice67([1, 2, 2]))

Post a Comment for "Looking For A More Elegant Solution To This"