+ 1
Isit possible to represent the following sequence with a Python range expression: 1,−1,2,−2,3,−3,4,−4?
2 Respostas
+ 2
A range consists of consecutive numbers like 1, 2, 3, 4 or 5, 7, 9, 11 (step = 2) or 100, 95, 90, 85 (step = -5) etc. In your range, 0 is missing (so it's not a range of consecutive numbers). The best representation I can think of (without using a loop) is to use a fancy sorting function like this:
r = range(-4, 5)
print(sorted(r, key = lambda n: (abs(n), -n))) # output: [0, 1, -1, 2, -2, 3, -3, 4, -4]
Or like this:
r = [*range(1, 5)]
r += [-n for n in r] # these are lists, not ranges
print(sorted(r, key = lambda n: (abs(n), -n))) # output: [1, -1, 2, -2, 3, -3, 4, -4]
But maybe I'm thinking too complicated.
0
Yeah i think so