def GetDistinguishableNames(keys, delimiter, prefixes_to_remove):
  """Reduce keys to a concise and distinguishable form.

  Example:
    GetDistinguishableNames(['Day.NewYork.BigApple', 'Night.NewYork.BigMelon'],
                            '.', ['Big'])
    results in {'Day.NewYork.BigApple': 'Day.Apple',
                'Night.NewYork.BigMelon': 'Night.Melon'}.

    If a key has all parts commonly shared with others, then include
    the last shared part in the names. E.g.,

    GetDistinguishableNames(['Day.NewYork', 'Day.NewYork.BigMelon'],
                            '.', ['Big'])
    results in {'Day.NewYork.BigApple': 'NewYork',
                'Night.NewYork.BigMelon': 'NewYork.Melon'}.

  Args:
    keys: The list of strings, each is delimited by parts.
    delimiter: The delimiter to separate parts of each string.
    prefixes_to_remove: The list of prefix strings to be removed from the parts.

  Returns:
    short_names: A dictionary of shortened keys.
  """

  def RemovePrefix(part, prefixes_to_remove):
    for prefix in prefixes_to_remove:
      if part.startswith(prefix):
        return part[len(prefix):]
    return part

  key_part_lists = [key.split(delimiter) for key in keys]
  shortest_length = min(len(part_list) for part_list in key_part_lists)

  # common_part[i] = True if all parts at position i are the same across keys.
  common_part = [True] * shortest_length
  for part_list in key_part_lists[1:]:
    for i in range(shortest_length):
      if part_list[i] != key_part_lists[0][i]:
        common_part[i] = False

  # The prefix list to add if one of the key happens to be the concatenation of
  # all common parts.
  prefix_list = ([key_part_lists[0][shortest_length - 1]]
                 if all(common_part) else [])

  short_names = {}
  for key, part_list in zip(keys, key_part_lists):
    short_names[key] = delimiter.join(prefix_list + [
        RemovePrefix(part, prefixes_to_remove)
        for n, part in enumerate(part_list)
        if n >= shortest_length or not common_part[n]])

  return short_names