Advertisement
mate2code

database to slugs (fun4)

May 28th, 2023 (edited)
1,204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. import itertools
  2. from collections import defaultdict
  3. from string import ascii_lowercase as alphabet
  4.  
  5. flatten = itertools.chain.from_iterable
  6. def double_generator(gen): return itertools.tee(gen, 2)
  7.  
  8.  
  9. database = {
  10.     0: {'name1': 'John', 'name2': 'Spam', 'born': '1985'},  # JohnSpam85a
  11.     1: {'name1': 'John', 'name2': 'Spam', 'born': '1985'},  # JohnSpam85b
  12.     2: {'name1': 'John', 'name2': 'Eggs', 'born': '1991'},  # JohnEggs91
  13.     3: {'name1': 'John', 'name2': 'Eggs', 'born': '1992'},  # JohnEggs92
  14.     4: {'name1': 'Emma', 'name2': 'Fish', 'born': '1995'},  # EmmaFish95a
  15.     5: {'name1': 'Emma', 'name2': 'Fish', 'born': '1995'},  # EmmaFish95b
  16.     6: {'name1': 'Mary', 'name2': 'Beer', 'born': '2000'},  # MaryBeer
  17.     7: {'name1': 'Mary', 'name2': 'Wine', 'born': '2000'},  # MaryWine
  18.     8: {'name1': 'Owen', 'name2': 'Wine', 'born': '2000'},  # Owen
  19.     9: {'name1': 'Ruth', 'name2': 'Milk', 'born': '2000'}   # Ruth
  20. }
  21.  
  22.  
  23. def find_duplicates(number_to_slug, dup_gen_to_refine):
  24.     slug_to_numbers = defaultdict(list)
  25.     if dup_gen_to_refine is not None:
  26.         for number in flatten(dup_gen_to_refine):
  27.             slug = number_to_slug[number]
  28.             slug_to_numbers[slug].append(number)
  29.     else:
  30.         for number, slug in number_to_slug.items():
  31.             slug_to_numbers[slug].append(number)
  32.     for block in slug_to_numbers.values():
  33.         if len(block) > 1:
  34.             yield block
  35.  
  36.  
  37. def find_slugs(database):
  38.  
  39.     """
  40.     Assign unique slugs to set of people. Slugs are as short as possible. (New elements only added to ensure uniqueness.)
  41.    https://codereview.stackexchange.com/questions/285146
  42.     """
  43.  
  44.     step_functions = [
  45.         lambda _, n: database[n]['name1'],
  46.         lambda _, n: database[n]['name2'],
  47.         lambda _, n: database[n]['born'][2:4],
  48.         lambda i, _: alphabet[i]
  49.     ]
  50.  
  51.     number_to_slug = {n: '' for n in database}
  52.     dup_gen_to_refine = None
  53.  
  54.     for step_fun in step_functions:
  55.         dup_gen = find_duplicates(number_to_slug, dup_gen_to_refine)
  56.         dup_gen_to_append, dup_gen_to_refine = double_generator(dup_gen)
  57.         for block in dup_gen_to_append:
  58.             for i, n in enumerate(block):
  59.                 number_to_slug[n] += step_fun(i, n)
  60.  
  61.     return number_to_slug
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement