I have the following code that works correctly. I am wondering if there is a simpler way to go about implementing my solution and/or if there is anything that looks non-standard in my code. If anyone wants to offer criticism I'm all ears.
### Question 2 main function and helper functions.
"""Given a string a, find the longest palindromic substring contained in a.
Your function definition should look like question2(a), and return a string."""
# Gives substrings of s in decending order.
def substrings(s):
# Declare local variable for the length of s.
l = len(s)
# Here I chose range over xrange for python version compatibility.
for end in range(l, 0, -1):
for i in range(l-end+1):
yield s[i: i+end]
# Define palindrome.
def palindrome(s):
return s == s[::-1]
# Main function.
def Question2(a):
for l in substrings(a):
if palindrome(l):
return l
# Simple test case.
print Question2("stresseddesserts")
# stresseddesserts
#...
above functions to docstrings inside functions. \$\endgroup\$s[i: i+end]
instead ofs[i:end]
. And look at the acrobatics you pull withfor i in range(l-end+1):
... that's really just a severely obfuscated way of writing nested loops with indicesfor i in range(l): ... for j in range(l, 0, -1):
then references[i:j]
\$\endgroup\$for l in substrings(a): ...
will return the first palindrome it finds inside a (stepping the indices back from the end), not just the longest one. If there are multiple longest palindromes it won't return them all. Your code is overly tailored to this one example. Use other examples to tickle it. \$\endgroup\$