Home > Blockchain >  Python program, list not printing
Python program, list not printing

Time:02-10

I have the following program which seeks to check the similarity between two lists. However, the originalword (list) prints correctly the first time but not the second therefore the code doesn't work to check equivalence.

https://trinket.io/python3/b3b7827717

Can anyone spot the error? If so, could a solution be posted a) using lists b) Not introducing any new skills (e.g. string slicing)

def palindromechecker():
  print("----Palindrome Checker---")
  
  word=input("Enter word:")
  
  #empty list for reversed word
  originalword=[]
  reversedword=[]
  
  #put each letter in word in the list originallist
  for i in range(len(word)):
    originalword.append(word[i])
  print("Print original word in order:",originalword)
  
  #reverse the word
  for i in range(len(word)):
    reversedword.append(originalword.pop()) 
  print("Reversed word:",reversedword)
  print("Original word:",originalword)
  
  #are original word and reversed word the same?
  
  if originalword==reversedword:
    print("--Palindrome Found--")
  else:
    print("--Not a Palindrome---")

palindromechecker()

CodePudding user response:

You make originalword list empty by doing that originalword.pop() in the second loop. Better way to do that is just reverse list like that

reversedword = originalword[::-1]

It will work without loop

Or you can do something like that:

for i in range(len(word)):
    reversedword.append(originalword[-1-i]) 

CodePudding user response:

If you use .pop() method, it will update the existing list by removing the last element from the list. So it is exhausting your originalword list.

I read that you don't want to use string[::-1]. Here is a similar but not the same workaround. You have to run the loop in reverse.

  #reverse the word
  for i in range(len(word)-1, -1, -1):
    reversedword.append(originalword[i]) 
  • Related