Write a recursive function palindrome_list ( arglist), where arglist is a list,
ID: 3706111 • Letter: W
Question
Write a recursive function palindrome_list(arglist), where arglist is a list, that returns True if and only if arglist is a palindrome, i.e., is the same sequence of elements whether it is traversed forwards from the first element or backwards from the last element.
Programming Requirements
Solve this problem using recursion. You are allowed to use onlythe following programming constructs:
if statements;
return statements;
assignment;
recursive function calls (but not to helper functions);
comparison operations (==, !=, etc.);
list indexing and slicing;
Boolean operations (and, or, not).
Solutions that go outside these constructs, e.g., by using for/while loops or list comprehensions, will not get credit.!!!!!!!!!!!!!!!!!!!!!
comment plz!
Explanation / Answer
Recursive function
def palindrome_list(arglist): #recursive function to traverse the list to check whether it is a palindrome
if len(arglist) < 2: return True #if the list contains only 1 element, then it is a palindrome
if arglist[0] != arglist[-1]: return False # if the list's first element and last element is not same, then it is not a palindrome
return palindrome_list(arglist[1:-1]) #call the function recursively with rest of elements in list excluding first and last element from the list
Test case to test the above function:
str = ['a','a']
if palindrome_list(str) == True:
print ('Is palindrome')
else:
print('Is not palindrome')
output:
Is palindrome
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.