i need to write a function that returns true if a list is a polindrom and false if it is not :
is_palindrome([]): True
is_palindrome([‘s’]): True
is_palindrome([1,4,'g','g',4,1]): True
is_palindrome(['a','c','v']): False
is_polindrom[1,"g","1]: false
this is my code :
import copy
def is_polindrom(lst):
if len(lst)<=1:
return True
copy_lst = copy.copy(lst)
reverse_copy = copy_lst.reverse()
for i,j in reverse_copy,copy_lst:
if reverse_copy[i].type()==copy_lst[j].type() and reverse_copy[i]==copy_lst[j]:
return True
else:
return False
is_polindrom([1,2])
when i use ["s"] instead of true is doesnt return anything and for :
is_polindrom([1,2]):
for i,j in reverse_copy,copy_lst:
TypeError: cannot unpack non-iterable NoneType object
i am not allowed to use negative or part indexes such as :
my_list[start:]
my_list[:end]
my_list[::step]
my_list[-idx]
my_list[:,idx]
thank you :)
Your code has 5 mistakes:
reverse_copy[i], copy_lst[j]
when you should just be doing
i, j
because in this case you are just iterating through each item, not through the INDEX of each item.
example_lst.reverse()
to reverse it.
i.type()
you must do
type(i)
for i, j in zip(lst1, lst2):
answer_list
then returnall(answer_list)
which returns True if answer_list
's items are all True.
(The reason is_polindrom returned False for [1, 2] was because you weren't using the zip() function so you weren't actually iterating through the items.)
Below is the full corrected code (note that I used Python's built-in list function to create a copy of lst):
def is_polindrom(lst):
if len(lst)<=1:
return True
copy_lst = list(lst)
reverse_copy = list(lst)
reverse_copy.reverse()
answer_list = []
for i,j in zip(reverse_copy,copy_lst):
if type(i)==type(j) and i==j:
answer_list.append(True)
else:
answer_list.append(False)
return all(answer_list)
lst = [1, 2]
# Prints is_polindrom([1, 2]): False
print("is_polindrom([1, 2]): " + str(is_polindrom(lst)))
print(lst) # Prints [1, 2]