Reputation: 1
I am currently creating a python script for a coding puzzle (advent of code) and the goal of the puzzle is to remove numbers from a list that meet certain criteria. The problem is my for loop only iterates through 3 of the 4 items in the list. Code:
def count(data, target_bit):
zero_count = 0
one_count = 0
for numbers in data:
if numbers[target_bit] == '0':
zero_count += 1
else:
one_count += 1
return [zero_count, one_count]
current_list = ["1001", "0001", "1111", "0011"]
oxygen_list = current_list
current_index = 1
zero_count = count(current_list, current_index)[0]
one_count = count(current_list, current_index)[1]
if zero_count > one_count:
loop_count = 0
for items in current_list:
print(loop_count)
if items[current_index] == "1":
oxygen_list.remove(current_list[loop_count])
loop_count += 1
print(current_list)
Upvotes: 0
Views: 76
Reputation: 375
if items[current_index] == "1":
oxygen_list.remove(current_list[loop_count])
this right here is removing the item where the 2nd number is 1
comment out these lines and you will see it will iterate over all 4 items in the list
Upvotes: 0
Reputation: 10477
This should be rule one of modifying lists: never remove items from a list while you're iterating over that list.
Instead, you can construct a new list and omit the items that don't fit:
if zero_count > one_count:
new_list = []
for items in current_list:
if items[current_index] == "0":
new_list.append(items)
current_list = new_list
You can do this more compactly with a list comprehension:
if zero_count > one_count:
current_list = [items for items in current_list if items[current_index] == "0"]
P.S.: I noticed you call count
twice, and throw away half of the results each time. Instead, you can do this:
zero_count, one_count = count(current_list, current_index)
Upvotes: 1