Unnecessary else
after return
In the body of an if
, if you end up returning something in that body, an else
is not required. A return will exit the body of the function, so the code in the else
won't be run. So, you can simply move the code in the else
to the outside, after the if
. This may have been confusing, but take a look at the updated code to see what I'm talking about.
enumerate()
Instead of using range(len())
, use enumerate()
. This will allow you to access both the index and the value at that position, and enumerate
works for other iterables as well. It's useful here because instead of writing arr[j]
over and over, you can simply write value
, which is the value at arr[j]
.
_
for unused loop variables
Also touching on enumerate
- When you only want to use one of the values (in your code, you have both cases present), use an _
in that place. This indicates to you and other readers that that variable is to be ignored, and isn't necessary.
Parameter Spacing
When using :
in parameters, make sure there is exactly one space after the :
.
Operator Spacing
Make sure to space out your operators when assigning and performing arithmetic on variables. It makes it much easier to read, and looks nicer.
return True
Instead of explicitly returning true
if the if
condition is true, simply return that condition. It will return the boolean value that is returned from that condition.
function_naming
I know you can't change the function names (assuming this is coming from a code challenge website), but remember that method names are to be in snake_case
, not camelCase
or PascalCase
. This is in reference to PEP-8 Method Naming Guidelines. Thanks to @SᴀᴍOnᴇᴌᴀ for pointing this out to me.
Updated Code
class Solution:
def longestPalindrome(self, s: 'str') -> 'str':
if s == "":
return ""
## Find all the substrings
arr = []
for i, value in enumerate(s):
char = value
arr.append(char)
for j in range(i + 1, len(s) - 1):
char += s[j]
arr.append(char)
##Find the palindrome with a longest length
max_length = 0
for _, value in enumerate(arr):
if self.isPalindrome(value):
if len(value) > max_length:
max_length = len(value)
index = value
return index
def isPalindrome(self, s: 'str')->'str':
return s == s[::-1]