+ 1

Isit possible to represent the following sequence with a Python range expression: 1,−1,2,−2,3,−3,4,−4?

22nd Dec 2018, 12:58 PM
Pradeep Kumar
Pradeep Kumar - avatar
2 RĂ©ponses
+ 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.
22nd Dec 2018, 2:07 PM
Anna
Anna - avatar
0
Yeah i think so
12th Oct 2020, 5:41 PM
Confused.exe