Metal.days
Metal.days

Reputation: 85

Iterating over a list until 2 conditions are met

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

Answers (2)

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

Prune
Prune

Reputation: 77837

Let's do this as we would on paper:

  • Find the first 6; mark the list up to that point.
  • In the rest of the list, find the first 7; mark the list after that point.
  • Combine the two marked list portions; sum those elements.

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

Related Questions