|
| 1 | +class LicenseKeyFormatter: |
| 2 | + def __init__(self, licenseKey): |
| 3 | + self.licenseKey = licenseKey.upper() |
| 4 | + |
| 5 | + |
| 6 | + def reformatLicenseKey(self, k): |
| 7 | + #first we count all the chars excluding dashes |
| 8 | + newLicenseKey = [] |
| 9 | + |
| 10 | + chars_count = 0 |
| 11 | + for c in self.licenseKey: |
| 12 | + if c != '-': |
| 13 | + chars_count += 1 |
| 14 | + |
| 15 | + #then lets define how many chars will be in our first group |
| 16 | + items_by_group = chars_count % k |
| 17 | + item_count = 0 |
| 18 | + |
| 19 | + for char_idx in range(len(self.licenseKey)): |
| 20 | + |
| 21 | + #Skip the dash char |
| 22 | + if self.licenseKey[char_idx] == '-': |
| 23 | + continue |
| 24 | + |
| 25 | + #condition to add a dash every items_by_group chars. |
| 26 | + #With this condition we prevent from adding a dash at the end of the new key. |
| 27 | + if item_count == items_by_group: |
| 28 | + |
| 29 | + #we this we prevent from adding a dash at the beginning of the new key |
| 30 | + if items_by_group != 0 and item_count != 0: |
| 31 | + newLicenseKey.append('-') |
| 32 | + |
| 33 | + items_by_group = k |
| 34 | + item_count = 0 |
| 35 | + |
| 36 | + #add the current char to our new licenseKey |
| 37 | + elm = self.licenseKey[char_idx] |
| 38 | + newLicenseKey.append(elm) |
| 39 | + |
| 40 | + item_count += 1 |
| 41 | + |
| 42 | + return ''.join(c for c in newLicenseKey) |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == '__main__': |
| 47 | + |
| 48 | + tests = [ |
| 49 | + {'input': {'licenseKey': '5F3Z-2e-9-w', 'k': 4}, 'expected': '5F3Z-2E9W'}, |
| 50 | + {'input': {'licenseKey': '2-5g-3-J', 'k': 2}, 'expected': '2-5G-3J'}, |
| 51 | + ] |
| 52 | + |
| 53 | + for test in tests: |
| 54 | + licenseKey = test['input']['licenseKey'] |
| 55 | + k = test['input']['k'] |
| 56 | + formatter = LicenseKeyFormatter(licenseKey) |
| 57 | + formattedLicenseKey = formatter.reformatLicenseKey(k) |
| 58 | + |
| 59 | + print('Input: (licenseKey=', licenseKey, ', k=', k, ')', ', Output: ', formattedLicenseKey, ', Expected: ', test['expected'], ', Test passed: ', ('True' if test['expected'] == formattedLicenseKey else 'False')) |
0 commit comments