Reputation: 85
I have a list, and I want to sum all the numbers in that list ... except that if a 6 comes up - that is not counted and any number from that 6, until a next 7 comes up (also not counting the 7). A 7 always will appear somewhere after a 6.
For example:
my_list = [1,2,3,6,1,1,1,7,2,2,2]
1,2,3,.........,2,2,2 # Omit numbers from the first 6 to the next 7.
should output 12.
I know how to identify the 6, I'm just not sure how to not count the numbers until a followup 7 comes.
Thank you.
Upvotes: 0
Views: 49
Reputation: 913
You can use a boolean as a flag. This should do it:
list= [1,2,3,6,1,1,1,7,2,2,2]
do_sum = True
total_sum = 0
for item in list:
if item == 6:
do_sum = False
if do_sum:
total_sum += item
if not do_sum and item == 7:
do_sum = True
The last if will check if the 6 went before the 7. So it will sum any seven that appears before a 6.
This solution supports multiple cases of sixes and sevens pairs in the list.
Upvotes: 1
Reputation: 77837
Let's do this as we would on paper:
6
; mark the list up to that point.Code, with a line of tracing output:
seq = [1, 2, 3, 6, 1, 1, 1, 7, 2, 2, 2]
first6 = seq.index(6)
rest = seq[first6:]
next7 = rest.index(7)
sum_list = seq[:first6] + rest[next7+1:]
print("Add these:", sum_list)
print("Sum:", sum(sum_list))
Output:
Add these: [1, 2, 3, 2, 2, 2]
Sum: 12
You can shorten the code by combining expressions, but I think this is more readable for you at this stage of your programming career.
Upvotes: 0