Created
October 21, 2022 06:53
-
-
Save bgalvao/cd241986a55af6cf5135c38432dc9563 to your computer and use it in GitHub Desktop.
Not a valid solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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