F L
F L

Reputation: 183

Simple logic explanation in loop?

I am trying to solve a loop-related logic problem. If I have an n-loop for, say, 50 iterations, and I want to extract only the value when the iteration is, say, n+10 (values at 10,20,30,40 and 50), what is the logic? (Lines in comments are my logic, which still resulted wrong output):

x[0] = 0
for n in xrange(0,50):
    x[n+1] = x[n] + 5
    #if x[n]%10==0:
        #y = x[n]

print x
#print y

Upvotes: 1

Views: 49

Answers (2)

Alex
Alex

Reputation: 19104

It looks like you have a list x and want set every value in x. Also you want y to be a subset of x (every 10th element).

x = [0] * 51
for n in range(50):
    x[n+1] = x[n] + 5
y = x[::10]

print(y)  # prints [0, 50, 100, 150, 200]

Upvotes: 1

Nathaniel Ford
Nathaniel Ford

Reputation: 21220

Your basic logic is correct. This is your algorithm:

For every element n between 0 and 50:
  if n is evenly divisible by ten
    return the value of n

Your implementation is a bit off, though. Try this:

x = list()
for n in range(0,50):
    if n % 10 == 0:  # Save the value if it's evenly divisible by ten
        x.append(n)

print(x)

In the REPL this gives the output:

>>> print(x)
>>> [0, 10, 20, 30, 40]

Note that if you don't need the other values (that are not evenly divisible by ten) there is no reason to save them to the array. The iteration will still loop through these values but, in this case, do nothing with them.

Upvotes: 1

Related Questions