Skip to content

Instantly share code, notes, and snippets.

@PyDann
Created March 20, 2014 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PyDann/182849dddc763ad46ccc to your computer and use it in GitHub Desktop.
Save PyDann/182849dddc763ad46ccc to your computer and use it in GitHub Desktop.
Compass
if x >= 340 or x <= 20:
return 'N'
elif x > 20 and x < 70:
return 'NE'
elif x >= 70 and x <= 110:
return 'E'
elif x > 110 and x < 160:
return 'SE'
elif x >= 160 and x <= 200:
return 'S'
elif x < 250 and x > 200:
return 'SW'
elif x >= 250 and x <= 290:
return 'W'
else:
return 'NW'
@cclauss
Copy link

cclauss commented Mar 20, 2014

import collections

def compass_dir_1(x = 0):
    if x >= 340 or x <= 20:
        return 'N'
    elif 20 < x < 70:  # optimization for 20 < x and x < 70
        return 'NE'
    elif 70 <= x <= 110:
        return 'E'
    elif 110 < x < 160:
        return 'SE'
    elif 160 <= x <= 200:
        return 'S'
    elif 200 < x < 250:
        return 'SW'
    elif 250 <= x <= 290:
        return 'W'
    else:
        return 'NW'

def compass_dir_2(x = 0):
    if x >= 340 or x <= 20:
        return 'N'
    if x < 70:  # no elifs
        return 'NE'
    if x <= 110:
        return 'E'
    if x < 160:
        return 'SE'
    if x <= 200:
        return 'S'
    if x < 250:
        return 'SW'
    if x <= 290:
        return 'W'
    else:
        return 'NW'

def compass_dir_3(x = 0):
    if x >= 340:
        return 'N'
    direction_dict = collections.OrderedDict([
        ( 21, 'N'),
        ( 70, 'NE'),
        (111, 'E'),
        (160, 'SE'),
        (201, 'S'),
        (250, 'SW'),
        (291, 'W'),
        (340, 'NW') ])
    for i in direction_dict.keys():
        if x < i:
            return direction_dict[i]

for i in range(360):
    print(i, compass_dir_1(i), compass_dir_2(i), compass_dir_3(i))
    assert compass_dir_1(i) == compass_dir_2(i) == compass_dir_3(i)

# negative user testing
i = -1
print(i, compass_dir_1(i), compass_dir_2(i), compass_dir_3(i))
i = 10000
print(i, compass_dir_1(i), compass_dir_2(i), compass_dir_3(i))
i = 'a'
print(i, compass_dir_1(i), compass_dir_2(i), compass_dir_3(i))

@PyDann
Copy link
Author

PyDann commented Mar 20, 2014

Your second solution should have been more obvious to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment