Skip to content

Instantly share code, notes, and snippets.

@zmarvel
Last active June 24, 2016 01:58
Show Gist options
  • Save zmarvel/daaf18bbae0713070c0892d928fc18fa to your computer and use it in GitHub Desktop.
Save zmarvel/daaf18bbae0713070c0892d928fc18fa to your computer and use it in GitHub Desktop.
A Python solution to the same problem as my 2.clj gist.
#!/usr/bin/env python3
# Given a list of "passwords" for which e.g. "abc" and "cba" or "cat" and "tac"
# are not considered unique but "abc" and "bac" are considered unique, count the
# unique words in the list.
#
# Usage: python3 2.py < words.txt
import sys
from collections.abc import Set
class PassSet(Set):
def __init__(self, *args):
self.data = set(self.normalize_value(arg) for arg in args)
def __contains__(self, value):
return self.normalize_value(value) in self.data
def __iter__(self):
return iter(self.data)
def __len__(self):
return len(self.data)
def add(self, value):
self.data.add(self.normalize_value(value))
def normalize_value(self, value):
"""Note that value must be a string."""
first, last = value[0], value[-1]
if first < last:
return value
else:
return ''.join(reversed(value))
def main():
pd = PassSet()
for line in sys.stdin: # note `line` ends with \n
pd.add(line.rstrip())
print(len(pd))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment