Skip to content

Instantly share code, notes, and snippets.

@leonmax
Last active March 27, 2020 03: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 leonmax/e2db93cddf7327e8b6f381e07646b3b7 to your computer and use it in GitHub Desktop.
Save leonmax/e2db93cddf7327e8b6f381e07646b3b7 to your computer and use it in GitHub Desktop.
Apple Interview question

The first code piece input[0] is required. If it is an empty string it will not work. This is just to be defensive (of course your probably need to check None or other types as well to be even more defensive)

One of the difference I have is a treat the first element no different from the rest. And I've made function and assert (tests) to verify them. If I see this in the exam, I know this is a experienced engineer who has a good sense how to test rather than relying on stardard output.

# input = "aappplllleeee"
input = ""
n = 1
output = ""
letter = input[0]
for i in range(0, len(input) - 1):
if input[i+1]:
if input[i+1] == letter:
n = n+1
else:
output = output + letter + str(n)
n = 1
letter = input[i+1]
print(output + letter + str(n))
def str_format(input):
output = ""
letter = ""
n = 0
for ch in input:
if ch != letter: # change to new letter
# flush the cache
if n:
output += letter + str(n)
# reset the cache
letter = ch
n = 0
n += 1
# flush the cache
if n:
output += letter + str(n)
return output
assert str_format("aappplllleeee") == "a2p3l4e4"
assert str_format("") == ""
class Formatter:
def __init__(self):
self.output = ""
self.letter = ""
self.count = 0
def _flush(self):
if self.count:
self.output += self.letter + str(self.count)
def str_format(self, input):
for ch in input:
if ch != self.letter:
self._flush()
self.letter = ch
self.count = 0
self.count += 1
self._flush()
return self.output
assert Formatter().str_format("aappplllleeee") == "a2p3l4e4"
assert Formatter().str_format("") == ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment