-4

Evens in the interval Print all even integers from the interval [a, b] in decreasing order.

Input example #1
2 7
Output example #1
6 4 2

here is my code:

a,b = map(int,input().split())
for i in reversed(range(a,b,2)):
   print(i,end=" ")

how can i do this without reversed?

  • range(b, a, -2) – aSaffary Sep 21 '21 at 06:33
  • dos not work for input "3 11" , "7 1", crashes for inputs that are not int-convertible or have more/less then exactly 2 ints, does not check the "even" condition of the task, does not work with bigger number put in first, but overall a start. – Patrick Artner Sep 21 '21 at 06:34
  • 1
    Remember you also need to handle the case where the start value is odd. – Ken Y-N Sep 21 '21 at 06:34

2 Answers2

1

You can ensure that b is even with b//2*2 and use range in reverse order:

list(range(b//2*2,a-1,-2))

output: [6, 4, 2]

But, honestly, if this is a nice learning example, for practical uses, go with reversed this will be more efficient (and explicit)

full code:

a,b = map(int,input().split())
for i in range(b//2*2,a-1,-2):
   print(i,end=" ")

For fun, here is a loop-less version:

print(' '.join(map(str, range(b//2*2,a-1,-2))))
mozway
  • 194,879
  • 13
  • 39
  • 75
0

You could transform your range into an array. Post here And then print them backward with [::-1]

a,b = map(int,input().split())
print([*range(a,b,2)][::-1])
LeauHic
  • 54
  • 5