I am trying to come up with an algorithm that will select 1 out of every 3 entries in a number sequence from 10 to 3010 and store it in a list in Python.
I have tried using an additional counter number that starts at 1, increments by one for every iteration of the sequence, and then gets reset back to 1 once it reaches the value of 4. The idea is that every time the counter is set 1, it will add a number from the sequence into my list:
excluded_values = []
i = 1
for index in range(10,3010):
if i == 1:
excluded_values.append(index)
i = 1
if i == 4:
i = 1
The problem is that when I request to print out the result of excluded values, I simply get the response of 10
.
excluded_values
10
CodePudding user response:
Your code does not work because the i = 1
is performed only with the condition i == 1
. This means that i assumes only values of 1 and 2, and never reaches the value of 4, and hence also never again the value 1. Here I amended your code, although I prefer the solution with range(10, 3010, 3)
suggested in the comments.
excluded_values = []
i = 1
for index in range(10,3010):
if i == 1:
excluded_values.append(index)
if i == 3:
i = 0
i = 1
print(excluded_values)
CodePudding user response:
when we already know the range, why run through each number in range and instead take steps. It produces the same result but faster
excluded_values = []
idx = 10
last_val = 3010
step = 3
while idx <= last_val:
excluded_values.append(idx)
idx =step
print(excluded_values)