-
Notifications
You must be signed in to change notification settings - Fork 0
/
subpalindrome.py
52 lines (46 loc) · 1.52 KB
/
subpalindrome.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# radar==radar
#
# --------------
# 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."
if text=='':return (0,0)
palindromes = [grow(text, start, end)
for start in range(len(text))
for end in (start, start+1) ]
print (palindromes)
return max(palindromes, key=length)
def length(slice):
a,b=slice
return b-a
def grow(text, start, end):
while (start >0 and end < len(text)
and text[start-1].upper() == text[end].upper() ):
start -=1; end +=1
return (start,end)
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'
print (test())