python how do i use abs for clockwise?

Question:

im trying to get absolute value between base_pos and postiion but clockwise.

position = [9,12,6]

base_pos = 3


position = sorted(position, key=lambda k: abs(k - base_pos))

print (position)

the code above will give the result of this

[6, 9, 12]

my desired result

[6, 12, 9] #or 
[12, 6, 9]

but i want to get [6,12,9] or [12,6,9] because for a clock, 3 is closer to 6 and 9 than 12.
is there any way to accomplish this using abs? if not, is there a good way to do this?

Asked By: kerz

||

Answers:

Computing distance (0 to 11) in both directions and taking the smaller:

sorted(position, key=lambda k: min((k-base_pos)%12, (base_pos-k)%12))
Answered By: Kelly Bundy

Your solution is on here

from math import cos, pi

position = [9,11,6,1,2,4,5,7,8,10,12,3]

base_pos = 3


position = sorted(position, key=lambda k: -cos((k%12 - base_pos) * pi / 6))

print (position)

Result

Answered By: Mehmet Güngören
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.