from functools import partial
def filter_inputis_palindrome(x, lower=Falseinput_str, filter_type='nofilter'):
"""
Parameter 'filter_type' defaults to pass-through, but you can
provide options such as 'alphanum', 'nospace' (to just get rid of
spaces), and 'alpha'
lower is a bool that checks if you want the string to be
case-insensitive
"""
filters = {
'alpha': partial(filter, str.isalpha),
'alphanum': partial(filter, str.isalnum),
'nospace': partial(filter, lambda char: not char.isspace()),
'nofilter': partial(map, lambda char: char) # this is just a pass-through
}
# raise this exception just so the use is more clear to the user
# what is expected
try:
f = filters[filter_type]
except KeyError as e:
raise ValueError(
f"Invalid filter_type, choose one of {'\n'.join(filters)}"
) from e
x return= ''.join(filter_type(
input_str.lower() if lower else input_str
))
def is_palindrome(x):
"""
Take an input string and return if it is a palindrome
"""
# you can just check the first half of the string
# against the last half reversed, rather than comparing the entire string
midpoint = len(x) // 2
if len(x) % 2: # even length
a = b = midpoint
else:
a, b = midpoint + 1, midpoint
return x[:a] == x[b::-1]
# which can be used like
mystr = 'abc123 321 BCA'
is_palindrome(mystr)
False
# won't lower-case and strips out non-alpha chars
is_palindrome(filter_input(mystr, filter_type='alpha'))
False
will lower-case and strips out spaces
is_palindrome(filter_input(mystr, lower=True, filter_type='nospaces'))
True