Skip to content

Instantly share code, notes, and snippets.

@ZechCodes
Last active June 12, 2020 08:18
Show Gist options
  • Save ZechCodes/361d19549456f89de69b86af26270274 to your computer and use it in GitHub Desktop.
Save ZechCodes/361d19549456f89de69b86af26270274 to your computer and use it in GitHub Desktop.
Challenge #25 - Directionally Challenged

Challenge #25 - Directionally Challenged

Suppose you are directionally challenged, and get lost easily. As a result, sometimes you walk in circles or make U-turns. You might take a sub-optimal route. Create a function that returns the difference in length between your path and the optimal path. Both paths reach the same destination.

You start at (0,0) and reach your destination by the end of the input list.

A demonstration

Your route: ["N", "S", "E", "W", "E", "E", "E", "N"]  // 8
Optimal route: ["E", "E", "E", "N"] (or ["N", "E", "E", "E"], etc.) // 4
# Difference in length: 8 - 4 = 4

# Explanation: Your "S" cancels out your "N" and your "W" cancels out your "E" leaving you back at (0,0)

Examples

route_diff(["N", "E", "S", "W"]) ➞ 4
# You"ve just walked in a circle! You are back at the origin. Your optimal path was `[]`.

route_diff(["N", "N", "N", "E", "N", "E"]) ➞ 0
# No improvements here!

route_diff(["N", "S", "N", "S", "E", "W", "E", "E"]) ➞ 6

Notes

  • Remember that a N cancels out a S, and an E cancels out a W.
import unittest
from typing import AnyStr, List
def route_difference(directions: List[AnyStr]) -> int:
return 0 # Put your code here!
class TestDirectionallyChallenged(unittest.TestCase):
def test_1(self):
self.assertEqual(route_difference(['N', 'E', 'S', 'W']), 4)
def test_2(self):
self.assertEqual(route_difference(['N', 'N', 'N', 'E', 'N', 'E']), 0)
def test_3(self):
self.assertEqual(route_difference(['N', 'S', 'N', 'S', 'E', 'W', 'E', 'E']), 6)
def test_4(self):
self.assertEqual(route_difference(['N', 'S', 'N', 'S', 'E']), 4)
def test_5(self):
self.assertEqual(route_difference(['N', 'N', 'S', 'S', 'S', 'S', 'E']), 4)
def test_6(self):
self.assertEqual(route_difference(['N', 'N', 'S', 'S', 'W', 'S', 'E']), 6)
def test_7(self):
self.assertEqual(route_difference(['N', 'S', 'E']), 2)
def test_8(self):
self.assertEqual(route_difference(['S', 'S', 'S']), 0)
def test_9(self):
self.assertEqual(route_difference(['S', 'S', 'S', 'S', 'S', 'N']), 2)
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment