0

Trying to print this pattern of numbers want this output:(if a=10)

    2
    9
    4
    7
    6
    5
    8
    3
    10
    1

CODE::

a=10
for i in range(1,a+1):
  if(i%2==0):
    print(i)
  elif(a-i%2!=0):
    print(a-i)
rama more
  • 1
  • 1
  • Great start. Whats the problem? Are you getting any error code or message specifically? – Aroic Dec 30 '19 at 17:22
  • You may now think about accepting an answer or comment one to get details ;) to reward those who spent time for you ;) – azro Jan 03 '20 at 15:23

3 Answers3

1

As you starts form 2 I'd suggest the loop do the same, then depending if the value if odd or even, print the good things

a = 10
for i in range(2, a + 2):
    if i % 2 == 0:
        print(i)
    else:
        print(a - i + 2)
azro
  • 53,056
  • 7
  • 34
  • 70
0

Have no idea what this problem is about, but keeping to your approach your style of code, you just need to flip every other value about, so:

a=10
for j in range(1,a+1):
  i = j + 1 if j % 2 else j - 1
  if(i%2==0):
    print(i)
  elif(a-i%2!=0):
    print(a-i)
Andrew Allaire
  • 1,162
  • 1
  • 11
  • 19
0

Another solution would be to run multiple iterators and run through them both:

a = 10
for i, j in zip(range(2, a + 2), range(a, 0, -1)):
    print(j if i % 2 else i)

Or you can create a single list with all the items:

a = 10
print([i for l in zip(range(2, a + 2, 2), range(a - 1, 0, -2)) for i in l])

The first range runs through the list forwards, and the second range runs backwards in each case.

Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
  • I like the second one because there is no [`if`-branching](https://stackoverflow.com/questions/315306/is-if-expensive) to slow the code down (scales well if this was in a generator) – Sunny Patel Dec 30 '19 at 17:43