Skip to content

Instantly share code, notes, and snippets.

@bgalvao
Created October 21, 2022 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgalvao/cd241986a55af6cf5135c38432dc9563 to your computer and use it in GitHub Desktop.
Save bgalvao/cd241986a55af6cf5135c38432dc9563 to your computer and use it in GitHub Desktop.
Not a valid solution
# codeinterview.io
# You are envolved in a development of a new binary serialization
# protocol. Your first task is to implemnt `enumerateChars`
# function. The function builds dictionary where key is character found in
# the strings and value corresponding coordinates of that character (string index
# in the sequence, character index in the string)
#
# Arguments:
# strings: list of strings
# Returns: mapping of each character
# found ifn `strings` to it's coordiantes `(x, y)`,
# where `x the index of string the character is part of and
# `y` the index of character inside the string.
# Indexing starts from 1.
# Example:
# For the `['zx', 'xy', 'ycaa', 'aca', 'c']` the result would be:
# {[(3,3),(3,4),(4,1),(4,3)]
# 'a' : ,
# 'c' : [(3,2),(4,2),(5,1)],
# 'x' : [(1,2),(2,1))],
# 'y' : [(2,2),(3,1))],
# 'z' : [(1,1)]
# }
#
from collections import OrderedDict
def task(strings: list) -> dict:
characters_index = {}
# O(n^2)
for i, string in enumerate(strings):
for j, character in enumerate(string):
if character in characters_index.keys():
characters_index[character].append((i+1, j+1))
else:
characters_index[character] = [(i+1, j+1)]
# [[{'a': (1)}, {'b': (2)}], [{'b': (1)}, {'a': (2)}]]
# O(n) + O(n)
map1 = map(
lambda tup:
{character: (tup[0], j) for (j, character) in enumerate(string)} , enumerate(strings))
print(list(map1))
return characters_index
# input
['ab', 'ba']
# 1st mapping
OrderedDict()
# print(task(['ab', 'ba']))
assert task(['ab', 'ba']) == {'a': [(1,1),(2,2)], 'b': [(1,2),(2,1)]}
assert task(['aa', 'aaa']) == {'a': [(1,1),(1,2),(2,1),(2,2),(2,3)]}
assert task(["zx", "xy", "ycaa", "aca", "c"]) == {'a' : [(3,3),(3,4),(4,1),(4,3)], 'c' : [(3,2),(4,2),(5,1)], 'x' : [(1,2),(2,1)], 'y' : [(2,2),(3,1)], 'z' : [(1,1)]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment