Skip to content

Instantly share code, notes, and snippets.

@anson-vandoren
Created March 9, 2019 17:10
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 anson-vandoren/542a67e92e149d9d063e187a689d015f to your computer and use it in GitHub Desktop.
Save anson-vandoren/542a67e92e149d9d063e187a689d015f to your computer and use it in GitHub Desktop.
Interview solutions (naive, no StackOverflow)
#######
# One #
#######
import re
def longest_prefix(str_list):
sorted_strs = sorted(str_list, key=lambda x: len(x))
longest = sorted_strs[-1]
return [
longest[:i]
for i, c in enumerate(longest)
for other in sorted_strs[:-1]
if not re.match(longest[: i + 1], other)
][0]
test_lists = [
["abcdefabc", "abcdfff", "abcodo"],
["aab", "adc", "aef"],
["abc", "def", "cbd"],
]
for l in test_lists:
print(longest_prefix(l))
#######
# Two #
#######
from string import ascii_letters
import re
def reverse_letters(test_str):
chars = [s for s in test_str if s in ascii_letters]
backward = iter(reversed(chars))
return re.sub(r"[a-zA-Z]", lambda x: next(backward), test_str, len(chars))
test_strings = [r"a#f*bc'", r"kcj&$ba#", r"&#*#", r"abcd%ef"]
for test in test_strings:
print(reverse_letters(test))
#########
# Three #
#########
def hits_zero(group):
nums, start = group
if start < 0 or start > len(nums) or nums[start] == "X":
return False
if nums[start] == 0:
return True
left, right = start - nums[start], start + nums[start]
nums[start] = "X"
return hits_zero((nums, left)) or hits_zero((nums, right))
test_groups = [
([3, 1, 0, 2, 4], 3),
([3, 1, 0, 2, 4], 0),
([1, 4, 0, 1, 3, 2], 4),
([1, 4, 0, 1, 3, 2], 0),
]
for group in test_groups:
print(hits_zero(group))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment