Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Last active March 30, 2016 08:46
Show Gist options
  • Select an option

  • Save sword-jin/0aa2e63647f9987c93775caa0323ebec to your computer and use it in GitHub Desktop.

Select an option

Save sword-jin/0aa2e63647f9987c93775caa0323ebec to your computer and use it in GitHub Desktop.
Subpalindrome
# --------------
# User Instructions
#
# Write a function, longest_subpalindrome_slice(text) that takes
# a string as input and returns the i and j indices that
# correspond to the beginning and end indices of the longest
# palindrome in the string.
#
# Grading Notes:
#
# You will only be marked correct if your function runs
# efficiently enough. We will be measuring efficency by counting
# the number of times you access each string. That count must be
# below a certain threshold to be marked correct.
#
# Please do not use regular expressions to solve this quiz!
def longest_subpalindrome_slice(text):
"Return (i, j) such that text[i:j] is the longest palindrome in text."
length = len(text)
text = text.lower()
return max([(i, j) for i in range(length + 1) for j in range(i, length + 1) if text[i:j] == text[i:j][::-1]], key=lambda x: abs(x[0] - x[1]))
def test():
L = longest_subpalindrome_slice
assert L('racecar') == (0, 7)
assert L('Racecar') == (0, 7)
assert L('RacecarX') == (0, 7)
assert L('Race carr') == (7, 9)
assert L('') == (0, 0)
assert L('something rac e car going') == (8,21)
assert L('xxxxx') == (0, 5)
assert L('Mad am I ma dam.') == (0, 15)
return 'tests pass'
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment