-7

I am looking at converting compass degrees to a string representing directions. There's another SO post to do this here.

This is one answer that modified slightly to represent the complete direction as a word Vs just the abbreviation, would anyone know how to convert this to a Python function? Im looking to have a string returned that represents the 8 cardinal directions... Answer by Edward Brey Feb 13 '19 at 18:29

function getCardinalDirection(angle) {
    const directions = ['↑ North', '↗ North East', '→ East', '↘ South East', '↓ South', '↙ South West', '← West', '↖ North West'];
    return directions[Math.round(angle / 45) % 8];
}
bbartling
  • 3,288
  • 9
  • 43
  • 88
  • 6
    Where is your attempt and what is the problem with that? There is nothing complicated about that function, it should be trivial to write it again in Python – UnholySheep Aug 06 '20 at 14:52

2 Answers2

2

It's more straightforward than you think:

def getCardinalDirection(angle):
    directions = ['↑ North', '↗ North East', '→ East', '↘ South East', '↓ South', '↙ South West', '← West', '↖ North West']
    return directions[round(angle / 45) % 8]  # round() is a built-in function

Example output:

>>> getCardinalDirection(50)
'↗ North East'
>>> getCardinalDirection(220)
'↙ South West'
>>> getCardinalDirection(-37)
'↖ North West'
>>> getCardinalDirection(188)
'↓ South'
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
0

as simple as it is:

def get_card_direction(angle):
    directions = ['↑ North', '↗ North East', '→ East', '↘ South East', '↓ South', '↙ South West', '← West', '↖ North West']
    return directions[round(angle/45) % 8]
print(get_card_direction(50)) # output ↗ North East
Tasnuva Leeya
  • 2,515
  • 1
  • 13
  • 21