Created
July 26, 2020 06:32
-
-
Save opethe1st/c2ff9878c777136533398cbc20902b66 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class State: | |
def __init__(self, state): | |
self.state = state | |
def transistion(self, inp): | |
pass | |
class Start(State): | |
def transistion(self, string, cursor): | |
inp = string[cursor] | |
if inp == '{': | |
return OneOpenBracket(self.state), '', cursor+1 | |
return Character(self.state), inp, cursor+1 | |
class Character(State): | |
def transistion(self, string, cursor): | |
inp = string[cursor] | |
if inp == '{': | |
return OneOpenBracket(self.state), '', cursor+1 | |
else: | |
return Character(self.state), inp, cursor+1 | |
class OneOpenBracket(State): | |
def transistion(self, string, cursor): | |
inp = string[cursor] | |
if inp == '{': | |
return Character(self.state), '{', cursor+1 | |
if inp in '0123456789': | |
number = '' | |
while cursor < len(string): | |
inp = string[cursor] | |
if inp in '0123456789': | |
number += inp | |
else: | |
break | |
cursor += 1 | |
if cursor < len(string) and string[cursor] == '}': | |
return EndBracket(self.state), self.state['replacements'][int(number)], cursor | |
else: | |
return Error(self.state), '', cursor | |
class PlaceHolder(State): | |
def transistion(self, string, cursor): | |
number = '' | |
while cursor < len(string): | |
inp = string[cursor] | |
if inp in '0123456789': | |
number += inp | |
else: | |
break | |
cursor += 1 | |
if cursor < len(string) and string[cursor] == '}': | |
return EndBracket(self.state), self.state['replacements'][int(number)], cursor | |
else: | |
return Error(self.state), '', cursor | |
class EndBracket(State): | |
def transistion(self, string, cursor): | |
inp = string[cursor] | |
if inp == '{': | |
return OneOpenBracket(self.state), '', cursor+1 | |
else: | |
return Character(self.state), '', cursor+1 | |
class Error(State): | |
def transistion(self, string, cursor): | |
return self | |
def solution(formatString, replacements): | |
state = Start({'replacements': replacements}) | |
ans = '' | |
cursor = 0 | |
for letter in formatString: | |
try: | |
state, output, cursor = state.transistion(formatString, cursor) | |
except Exception: | |
return '' | |
ans += output | |
if isinstance(state, Error): | |
return '' | |
if isinstance(state, PlaceHolder): | |
return '' | |
if isinstance(state, OneOpenBracket): | |
return '' | |
return ans | |
if __name__ == '__main__': | |
print(solution("A {{{0} {2} with {0} {1}}{.", ["fun", "activities", "party"])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment