Skip to content

Instantly share code, notes, and snippets.

@Semant1ka
Created January 25, 2022 03:35
Show Gist options
  • Save Semant1ka/60a5b3dc5216edf945d16cd747fb3cc1 to your computer and use it in GitHub Desktop.
Save Semant1ka/60a5b3dc5216edf945d16cd747fb3cc1 to your computer and use it in GitHub Desktop.
Interview problem #1
from collections import OrderedDict, defaultdict
def add_tags(obj, string):
# remember the index of each element
indexes = {k: v for k, v in enumerate(string)}
# formatting
formatting = defaultdict(list)
for k, v in obj.items():
start, end = v
if k == 'italics':
style = 'i'
elif k == 'bold':
style = 'b'
else:
style = k
for i in range(start, end + 1):
formatting[i].append(style)
# each index has a list of formats it should support, let's build anew string
result = []
for k, v in indexes.items():
if k in formatting:
result.extend([f"<{x}>" for x in formatting[k]])
result.append(v)
result.extend([f"</{x}>" for x in formatting[k][::-1]])
else:
result.append(v)
print("".join(result))
add_tags({"bold": [0, 2], "italics": [1, 3]}, "ABCDE")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment