Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import itertools
- from collections import defaultdict
- from string import ascii_lowercase as alphabet
- flatten = itertools.chain.from_iterable
- def double_generator(gen): return itertools.tee(gen, 2)
- database = {
- 0: {'name1': 'John', 'name2': 'Spam', 'born': '1985'}, # JohnSpam85a
- 1: {'name1': 'John', 'name2': 'Spam', 'born': '1985'}, # JohnSpam85b
- 2: {'name1': 'John', 'name2': 'Eggs', 'born': '1991'}, # JohnEggs91
- 3: {'name1': 'John', 'name2': 'Eggs', 'born': '1992'}, # JohnEggs92
- 4: {'name1': 'Emma', 'name2': 'Fish', 'born': '1995'}, # EmmaFish95a
- 5: {'name1': 'Emma', 'name2': 'Fish', 'born': '1995'}, # EmmaFish95b
- 6: {'name1': 'Mary', 'name2': 'Beer', 'born': '2000'}, # MaryBeer
- 7: {'name1': 'Mary', 'name2': 'Wine', 'born': '2000'}, # MaryWine
- 8: {'name1': 'Owen', 'name2': 'Wine', 'born': '2000'}, # Owen
- 9: {'name1': 'Ruth', 'name2': 'Milk', 'born': '2000'} # Ruth
- }
- def find_duplicates(number_to_slug, dup_gen_to_refine):
- slug_to_numbers = defaultdict(list)
- if dup_gen_to_refine is not None:
- for number in flatten(dup_gen_to_refine):
- slug = number_to_slug[number]
- slug_to_numbers[slug].append(number)
- else:
- for number, slug in number_to_slug.items():
- slug_to_numbers[slug].append(number)
- for block in slug_to_numbers.values():
- if len(block) > 1:
- yield block
- def find_slugs(database):
- """
- Assign unique slugs to set of people. Slugs are as short as possible. (New elements only added to ensure uniqueness.)
- https://codereview.stackexchange.com/questions/285146
- """
- step_functions = [
- lambda _, n: database[n]['name1'],
- lambda _, n: database[n]['name2'],
- lambda _, n: database[n]['born'][2:4],
- lambda i, _: alphabet[i]
- ]
- number_to_slug = {n: '' for n in database}
- dup_gen_to_refine = None
- for step_fun in step_functions:
- dup_gen = find_duplicates(number_to_slug, dup_gen_to_refine)
- dup_gen_to_append, dup_gen_to_refine = double_generator(dup_gen)
- for block in dup_gen_to_append:
- for i, n in enumerate(block):
- number_to_slug[n] += step_fun(i, n)
- return number_to_slug
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement