MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / _plugboard

Function _plugboard

ciphers/enigma_machine2.py:114–164  ·  view source on GitHub ↗

https://en.wikipedia.org/wiki/Enigma_machine#Plugboard >>> _plugboard('PICTURES') {'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'} >>> _plugboard('POLAND') {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'} In the code, ``pb`` stan

(pbstring: str)

Source from the content-addressed store, hash-verified

112
113
114def _plugboard(pbstring: str) -> dict[str, str]:
115 """
116 https://en.wikipedia.org/wiki/Enigma_machine#Plugboard
117
118 >>> _plugboard('PICTURES')
119 {'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'}
120 >>> _plugboard('POLAND')
121 {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}
122
123 In the code, ``pb`` stands for ``plugboard``
124
125 Pairs can be separated by spaces
126
127 :param pbstring: string containing plugboard setting for the Enigma machine
128 :return: dictionary containing converted pairs
129 """
130
131 # tests the input string if it
132 # a) is type string
133 # b) has even length (so pairs can be made)
134 if not isinstance(pbstring, str):
135 msg = f"Plugboard setting isn't type string ({type(pbstring)})"
136 raise TypeError(msg)
137 elif len(pbstring) % 2 != 0:
138 msg = f"Odd number of symbols ({len(pbstring)})"
139 raise Exception(msg)
140 elif pbstring == "":
141 return {}
142
143 pbstring.replace(" ", "")
144
145 # Checks if all characters are unique
146 tmppbl = set()
147 for i in pbstring:
148 if i not in abc:
149 msg = f"'{i}' not in list of symbols"
150 raise Exception(msg)
151 elif i in tmppbl:
152 msg = f"Duplicate symbol ({i})"
153 raise Exception(msg)
154 else:
155 tmppbl.add(i)
156 del tmppbl
157
158 # Created the dictionary
159 pb = {}
160 for j in range(0, len(pbstring) - 1, 2):
161 pb[pbstring[j]] = pbstring[j + 1]
162 pb[pbstring[j + 1]] = pbstring[j]
163
164 return pb
165
166
167def enigma(

Callers 1

_validatorFunction · 0.85

Calls 1

addMethod · 0.45

Tested by

no test coverage detected