I'm new to programming and I'm trying to do the codingbat.com problems to start. I came across this problem:
Given an array calculate the sum except when there is a 13 in the array. If there is a 13 in the array, skip the 13 and the number immediately following it. For example [1,2,13,5,1] should yield 4 (since the 13 and the 5s are skipped).
This is what I have so far. My problem is that I don't know what to do when there are multiple 13s...And I would like to learn coding efficiently. Can you guys help? (I'm using python 3.2) Thanks!
def pos(nums):
for i in nums:
if i == 13:
return nums.index(13)
return False
def sum13(lis):
if pos(lis)!= False:
return sum(lis[:pos(lis)])+sum(lis[pos(lis)+1:])
else:
return sum(lis)
One tricky thing to notice is something like this: [1, 13, 13, 2, 3]
You need to skip 2
too
def getSum(l):
sum = 0
skip = False
for i in l:
if i == 13:
skip = True
continue
if skip:
skip = False
continue
sum += i
return sum
Explanation:
You go through the items in the list one by one
Each time you
skip
as True
, so that you can also skip next item.skip
is True
, if it is, which means it's a item right after 13, so you need to skip this one too, and you also need to set skip
back to False
so that you don't skip next item.sum
You can use the zip function to loop the values in pairs:
def special_sum(numbers):
s = 0
for (prev, current) in zip([None] + numbers[:-1], numbers):
if prev != 13 and current != 13:
s += current
return s
or you can do a oneliner:
def special_sum(numbers):
return sum(current for (prev, current) in zip([None] + numbers[:-1], numbers)
if prev != 13 and current != 13)
You can also use iterators:
from itertools import izip, chain
def special_sum(numbers):
return sum(current for (prev, current) in izip(chain([None], numbers), numbers)
if prev != 13 and current != 13)
(the first list in the izip is longer than the second, zip and izip ignore the extra values).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With