'Sum of numbers in array, not counting 13 and number directly after it (CodingBat puzzle)
The Question:
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
My Code:
def sum13(nums):
l = len(nums)
tot = 0
if l==0:
return 0
for x in range(l):
if nums[x]!=13:
if nums[x-1]!=13:
tot+=nums[x]
return tot
Where It's Failing:
sum13([1, 2, 2, 1, 13]) should → 6, but my code is outputting 5
sum13([1, 2, 13, 2, 1, 13]) should → 4, but my code is outputting 3
Solution 1:[1]
Your problem is when x is zero. x - 1 will be -1 so it will get the last element of your list (13). To fix it, don't test x - 1 if x is zero:
if x == 0 or nums[x-1] != 13:
In Python, when you pass a negative index to a list it accesses its elements backwards, so:
>>> x = [1,2,3,4,5]
>>> x[-1]
5
>>> x[-2]
4
Solution 2:[2]
enumerate() can give the index, then it can be done using a generator expression in sum(). The extra 0 added to the end of the list makes it work for nums[i-1] when i = 0.
def sum13(nums):
nums += [0]
return sum(n for i, n in enumerate(nums) if n != 13 and nums[i-1] != 13)
Solution 3:[3]
Here is the solution:
def sum13(nums):
if len(nums) == 0:
return 0
for i in range(0, len(nums)):
if nums[i] == 13:
nums[i] = 0
if i+1 < len(nums):
nums[i+1] = 0
return sum(nums)
Solution 4:[4]
You could avoid the bug by using next() function instead of error-prone indexes:
def exclude13(iterable):
it = iter(iterable)
for x in it:
if x == 13: # don't yield 13
next(it) # skip number immediately after 13
else:
yield x
print(sum(exclude13([1, 2, 2, 1, 13]))) # -> 6
print(sum(exclude13([1, 2, 13, 2, 1, 13]))) # -> 4
Solution 5:[5]
def sum13(nums):
count = 0
while count < len(nums):
if nums[count] == 13:
del nums[count:count+2]
continue
count += 1
return sum(nums)
Solution 6:[6]
def sum13(nums):
count = 0
sum = 0
for i in range(len(nums)):
if nums[i] == 13 or sum == 1 :
nums[i]= 0
sum = sum + 1
count = count + nums[i]
if sum == 2:
sum = 0
if nums == []:
return 0
return coun
Solution 7:[7]
def sum13(nums):
if len(nums)==0:
return 0
sum=0
for i in range(1,len(nums)):
if nums[i]==13 or nums[i-1]==13:
sum = sum
else:
sum += nums[i]
if nums[0]==13:
return sum
else:
return sum + nums[0]
Start the loop form 1 and add back the first number (if it's not 13) at the end.
Solution 8:[8]
Make a copy of the list so that the original doesn't change, remove instances of the number 13 and the number immediately following, then sum the resulting list:
def sum13(nums):
nums = nums[:]
while 13 in nums:
i = nums.index(13)
del nums[i:i+2]
return sum(nums)
This is similar to the top answer for this problem: looking for a more elegant solution to this
Solution 9:[9]
Another way to look at it:
def sum13(nums):
sub = 0
for i in range(len(nums)):
if nums[i] == 13 :
sub+=nums[i]
if i+1<len(nums) and nums[i+1]!=13:
sub+=nums[i+1]
return sum(nums)-sub
Solution 10:[10]
def sum13(nums):
sum = 0
len_n = len(nums)
k = 0
while k < len_n:
if nums[k] == 13:
k += 2
else:
sum += nums[k]
k += 1
return sum
Solution 11:[11]
sum of list except when item=13 will not be counted and item+1 also be not counted
def sum13(nums):
if len(nums)==0:
return 0
if nums[-1]==13:
nums[-1]=0
for i in range(len(nums)-1):
if nums[i]==13:
nums[i]=0
nums[i+1]=0
return sum(nums)
Solution 12:[12]
def sum13(nums):
result = 0
i = 0
while i < len(nums):
if nums[i] == 13:
i += 2
continue
else:
result += nums[i]
i += 1
return result
Solution 13:[13]
You're excluding numbers that come immediately before a 13 when you should be excluding numbers that come immediately after.
Solution 14:[14]
I would suggest to use a recursive solution. Note that while index of a list can be out of range the slicing gives an empty list and not an error, e.g. if a = [1,1,2] then a[3] would give an error while a[3:] gives the empty list [].
def sum13(nums):
if len(nums) == 0:
return 0
sum = sum13(nums[1:])
if nums[0] != 13:
return sum + nums[0]
if nums[0] == 13:
return sum13(nums[2:])
Solution 15:[15]
I solved the problem in the following fashion. It is brute force, but it does work:
def sum13(nums):
count = 0
if len(nums) == 0:
return 0
for ans in range(len(nums)):
if nums[ans] == 13 and ans < len(nums)-1:
nums[ans] = 0
nums[ans+1] = 0
elif nums[ans] == 13 and ans == len(nums)-1:
nums[ans] = 0
else:
count += nums[ans]
return count
Solution 16:[16]
def sum13(nums):
nums2 = []
if 13 in nums:
for i in range(len(nums)-1): # the -1 is needed to avoid out of range.
if nums[i] != 13: nums2.append(nums[i])
else:
nums[i] = 0
nums[i+1] = 0
return sum(nums2)
return sum(nums)
I created a separate list and appended the figures i wanted into that list. i did this through a for loops by going through every element and appending that figure if it did not equal 13.
when it did eventually equal the number 13 i would then change that number by setting it to zero (nums[i] = 0). Then I also need to set the next number to it at Zero by indexing (nums[i+1] = 0). so they are then discounted from the sum of the list.
this is not a perfect solution but it is a working one.
Solution 17:[17]
This is an approach that i have taken,this works as well
nums = [1, 2, 2, 1, 13,2,1,2,3,13,4,5]
counter = 0
temp = []
for i in range(len(nums)):
if nums[i] == 13:
if (i+1) != len(nums) and nums[i+1] != 13:
temp.append(nums[i+1])
continue
elif (i+1) == len(nums):
continue
else:
counter = counter + nums[i]
temp_total = sum(temp)
count_total = counter - temp_total
print(count_total)
Solution 18:[18]
When x=0 in nums[x-1] it conflicts, because it results as nums[0-1] if it is 13 then it may not add so check nums[0] at last.
def sum13(nums):
co=0
if len(nums)<=0:
return co
for a in range(1,len(nums)):
if nums[a]==13:
continue
elif nums[a-1]==13:
continue
else:
co=co+nums[a]
if nums[0]!=13:
co+=nums[0]
return co
Solution 19:[19]
This is my solution for this exercise!!!!
def sum13(nums):
total = 0
for i in range(len(nums)):
if (nums[i] == 13 or nums[i-1] == 13 and i != 0):
total = total
else:
total += nums[i]
return total
Solution 20:[20]
def sum13(nums):
sum=0
ind13=[]
for num in nums:
if num==13:
num=0
ind13=nums.index(13)
ind13next=ind13+1
nums[ind13]=0
if nums[ind13] !=nums[-1]:
nums[ind13next]=0
sum=sum+num
else:
sum=sum+num
return sum
Solution 21:[21]
def sum13(nums):
summed=0
flag=True
index_13=0
for index, num in enumerate(nums):
if num==13:
index_13=index
flag=False
if flag==True:
summed=summed+num
if index_13+1<= len(nums)-1 and num==nums[index_13+1]:
flag=True
return summed
Solution 22:[22]
def sum13(nums):
li=[]
if nums[-1]==13:
li.append(13)
for i in range(len(nums)-1):
if nums[i]==13:
li.append(nums[i])
li.append(nums[i+1])
n=sum(nums)
return (n-sum(li))
Solution 23:[23]
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
def sum13(nums):
nums += [0]
add=sum(j for i, j in enumerate(nums) if j != 13 and nums[i-1] != 13)
return add
Solution 24:[24]
def sum13(nums):
sum=0
count=0
for i in range(len(nums)):
if nums[i]!=13:
count=count-1
if count<=0:
sum=sum+nums[i]
else:
count=2
return sum
Solution 25:[25]
The way I think about the problem lends me to loop over the list - except for the last element. Then if a value is 13, the next element becomes 0. From there - I reload the list - and replace ALL 13 with 0. In the end I simply sum the values of the list.
def sum13(nums):
for i,x in enumerate(range(len(nums)-1)):
if (nums[x]==13):
nums[i+1]=0
nums=nums
for i,x in enumerate(nums):
if x==13: #if the element is equal to 13
nums[i]=0
return sum(nums)
Solution 26:[26]
This should work as well. Basically it's a double continue statement. You assign pairs of index and value for each iteration with enumerate(). If a number is == 13 --> continue, the next iterated item should qualify for the elif statement, which also continues for items preceded by a 13. Elif runs only for items at indices >= 1 (so there is no issue with going out of range at [0]).
def sum13(nums):
if nums ==[]:
return 0
sum = 0
for index, val in enumerate(nums):
if nums[index] == 13:
continue
elif nums[index-1] == 13 and index > 0:
continue
else:
sum += val
return sum
Solution 27:[27]
def sum13(nums):
total = sum(nums)
for i in range (len(nums)):
if nums[i]==13:
total = total - nums[i]
if (i+1) < len(nums) and nums[i+1]!=13: #Using !=13 because 13 will already
total = total-nums[i+1] #be detected from previous if
return total
Solution 28:[28]
def sum13(nums):
if len(nums) == 0:
return 0
total = 0
for i in range(len(nums)):
if nums[i] == 13 and (len(nums)-1)>i:
nums[i+1]=0
total = total
elif nums[i]==13:
total = total
else:
total = total +nums[i]
return total
Solution 29:[29]
here another solution :
def sum13(nums):
for i in range (len(nums)) :
if nums[i] == 13 :
nums[i] = 0
if i+1 < len(nums) and nums[i+1] != 13 :
nums[i+1] = 0
return sum(nums)
Solution 30:[30]
This is how I have tried:)
sum = 0
for i in range(len(a)):
if a[i] == 13:
if i+1 < len(a):
a[i], a[i+1] = 0, 0
else:
a[i] = 0
else:
sum += a[i]
return sum
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
