write-ups-challenges-2020-2021/fancy_text/solution.py

65 lines
1.7 KiB
Python
Raw Permalink Normal View History

2022-11-24 17:03:20 +00:00
#
# SOLUTION: Fancy Letters
# by Benjamin Vermunicht
#
# Approach:
# We'll first try to build a dictionary mapping each letter
# in ascii-art to the real letter. Than we'll request a string
# and translate it with our dictionary.
#
# A dictionary with how each character looks
translation = {}
# Function to split a ascii-art string in ascii-art letters
# returns a list of srings, each string representing a letter
def readCharacters(asciiString):
characters = []
# splits each line of the ascii-art, lines will be
# iterated synchronously
asciiLines = asciiString.split('\n')[:-1]
thisChar = [''] * len(asciiLines)
for i in range(0, len(asciiLines[0])):
space = True
for j in range(0, len(asciiLines)):
# if all lines contain a space on the same index,
# we detect a new letter
if (asciiLines[j][i] != ' '):
space = False
thisChar[j] += asciiLines[j][i]
if space:
# if we detect a new letter, save the previou letter
# to our output
for j in range(0, len(asciiLines)):
thisChar[j] = thisChar[j][:-1]
# merge the characters of this character of each line
# to one string with newlines
characters.append('\n'.join(thisChar))
thisChar = [''] * len(asciiLines)
# save the last letter to the output
characters.append('\n'.join(thisChar))
return characters
# Iterates all characters of a known string to build
# a dictionary
def buildDictionary(asciiString, knownString):
i = 0
for c in readCharacters(asciiString):
translation[c] = knownString[i]
i += 1
# Translates an ascii-art string to regular text
# using the dictionary created with buildDictionary()
def translateString(asciiString):
resultString = ''
for c in readCharacters(asciiString):
resultString += translation[c]
return resultString