Home > database >  python how do i use abs for clockwise?
python how do i use abs for clockwise?

Time:01-03

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?

CodePudding user response:

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

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

CodePudding user response:

Your solution is on here

from math import cos
from math import 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 - base_pos) * pi / 6))

print (position)

Result

  • Related