1

I need to make a code that sorts a list of words and puts them in lexicographical order from reverse. For example, given the list ["harry", "harra", harrb"] I need a way to reverse each word so the list becomes ["yrrah", "arrah","brrah"]. Then I need to sort it by lexicographical order and reverse it back to its original order. So it would look like ["harra", "harrb", "harry"]. Im taking words from a file 'ifile' but for this code I'm only ordering words with a certain number of letters "n".

Here is my code so far:

def getRhymeSortedCount(n,ifile,file):
    word_list = []
    for word in ifile:
        if len(word) == n:
            word_list.append(word.strip())
    arr = word_list
    arr.sort(key = lambda x : x[::-1])
    ofile.write("\n".join(word_list))

it correctly orders the words by their last letter, but isnt taking the words with number of letters = "n" how can i change my len statement to grab only the words with n letters?

  • 1
    Basically it puts it in lexicographical order from the end of each word, but still lists them as the words in the original list. so it reverses the words, sorts them, then reverses them again – expertinthemaking22 May 20 '16 at 18:27

3 Answers3

6

Specify the key to sort to be the reversed string

word_list = ["harry","harra", "harrb"]
word_list.sort(key=lambda str: str[::-1])
T. Claverie
  • 11,380
  • 1
  • 17
  • 28
  • i need it to word for a full list of words that has like 21,000 words. so instead of writing word_list = ["harry", "harra", "harrb"] what should i write? – expertinthemaking22 May 20 '16 at 18:34
  • It depends of where the words are. If you get them from a file, then read the file and put them in a list. – T. Claverie May 20 '16 at 18:36
  • @expertinthemaking22 You already have that code to create the list in your own question. Not _your_ code? – BlackJack May 20 '16 at 18:49
2

Use a simple lambda function -

arr = ["harry","harra", "harrb"]

arr.sort(key = lambda x : x[::-1])

print(arr)

Output -

['harra', 'harrb', 'harry']
Vedang Mehta
  • 2,214
  • 9
  • 22
0

feels like you want someone to do you homework for you - so here's an answer you'll have to unpack a little to understand

word_list = ['harry', 'harra', 'harrb', "ignore_me"]
[y[::-1] for y in sorted([ x[::-1] for x in word_list if len(x) == 5])]

things to learn here:

  • list comprehension [ f(x) for x in list_of_xs if expression ]
  • you can slice strings as characters lists (and in reverse, too)
  • sorted(mylist) returns a sorted version of the list
  • while you're here check out reversed(mylist), even though its not used here. you can nest these : reversed(sorted(mylist)) - neat! (but not used in my solution)

(ohh, i like the lambda answers)