changeset 49:160e1bd59965

Plugboard now has methods to output state as a string for easier display.
author Brian Neal <bgneal@gmail.com>
date Tue, 19 Jun 2012 19:02:37 -0500
parents c4586511d320
children f3af458a5d2d
files enigma/plugboard.py enigma/tests/test_plugboard.py
diffstat 2 files changed, 38 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/enigma/plugboard.py	Tue Jun 05 19:41:04 2012 -0500
+++ b/enigma/plugboard.py	Tue Jun 19 19:02:37 2012 -0500
@@ -134,6 +134,33 @@
 
         return cls(wiring_pairs)
 
+    def get_pairs(self):
+        """Return the connections as a set of tuple pairs."""
+        pairs = set()
+        for x in range(0, 26):
+            y = self.wiring_map[x]
+            if x != y and (y, x) not in pairs:
+                pairs.add((x, y))
+
+        return pairs
+
+    def army_str(self):
+        """Return settings as a string as found on an army key sheet."""
+        pairs = list(self.get_pairs())
+        pairs.sort()
+        return ' '.join('{}{}'.format(chr(t[0] + ord('A')), 
+                                      chr(t[1] + ord('A'))) for t in pairs)
+
+    def navy_str(self):
+        """Return settings as a string as found on a navy key sheet."""
+        pairs = list(self.get_pairs())
+        pairs.sort()
+        return ' '.join('{}/{}'.format(t[0] + 1, t[1] + 1) for t in pairs)
+
+    def __str__(self):
+        """Returns a string representation of the settings in army format."""
+        return self.army_str()
+
     def signal(self, n):
         """Simulate a signal entering the plugboard on wire n, where n must be
         an integer between 0 and 25.
--- a/enigma/tests/test_plugboard.py	Tue Jun 05 19:41:04 2012 -0500
+++ b/enigma/tests/test_plugboard.py	Tue Jun 19 19:02:37 2012 -0500
@@ -112,3 +112,14 @@
                 self.assertEqual(p.signal(n), wiring[n])
             else:
                 self.assertEqual(p.signal(n), n)
+
+    def test_str(self):
+
+        stecker = 'AB CD EF GH IJ KL MN OP QR ST'
+        p = Plugboard.from_key_sheet(stecker)
+
+        self.assertEqual(stecker, p.army_str())
+        self.assertEqual(stecker, str(p))
+
+        navy = '1/2 3/4 5/6 7/8 9/10 11/12 13/14 15/16 17/18 19/20'
+        self.assertEqual(navy, p.navy_str())