3

I'm working on a problem in 'Python for Everyone', chapter 7. The program is meant to take a file and reproduce that file in reverse order of characters. This code makes a list of the characters as they appear, but when I use:

reversedList = sorted(charList, key=itemgetter(1), reverse=True)

I get: IndexError: string index out of range. This is the full code:

from _operator import itemgetter

def main():
     file = input("Enter the name of the file to be reversed: ")
     file = open(file, "r")
     charList = []
     char = file.read(1)
     charList.append(char[0])
     while char != "" :
        char = file.read(1)
        charList.append(char)

     reversedList = sorted(charList, key=itemgetter(1), reverse=True)
     file.close()

main()

Please let me know what is going wrong here.

grainman
  • 73
  • 7

1 Answers1

1

I don't get why you want to sort, you can simply use:

reversedList = charList[::-1]

[::-1] reversed lists, tuples, etc.

itemgetter(..) will not work here, since it does the opposite of what you want: itemgetter(value) generates a function that expects the list and returns the index of value, but key does not expect a function that maps list on indices, it expects a function that transforms elements to a metric to sort upon.

Something that would work, but would be very efficient is:

sorted(charList, key=charList.index, reverse=True)

Nevertheless I don't think the book wants you to use sorted, if you want to write a reverse function yourself, you could use for instance:

reversedList = []
for i in range(len(charList)-1,-1,-1):
    reversedList.append(charList[i])
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555