0

I am having trouble with the sorting by alphabetical order or possibly the displaying it that way part. it should do this Enter a sentence: An avocado a appeared 3 times

o appeared 2 times

c appeared 1 times d appeared 1 times n appeared 1 times v appeared 1 times

however mine does not sort by alphabetically after the number of times.

here is my code

sentence = input('Enter a sentence: ')
sentence = sentence.lower()
dictionary = {}
sort = {}
for n in sentence:
    keys = dictionary.keys()
    if n.isalpha():
        if n in keys:
            dictionary[n] += 1
        else:
            dictionary[n] = 1

sort = sorted(dictionary.items(), key = lambda letter:letter[1], reverse = True)
print()
print('Sentence Statistics:')

for x in sort:
    if x[0].isalpha:
        print(x[0], 'appeared', x[1],'times.')
    else:
        continue
Archer15
  • 1
  • 1
  • This specific answer is a clue https://stackoverflow.com/a/17109098/1317713 Your key should be a tuple of two elements: occurence count, then the letter itself. – Leonid Mar 21 '19 at 02:24
  • Because you never ask python to sort it. You may do some magic like this `sort = sorted(dictionary.items(), key = lambda letter: str(10000000-letter[1]) + letter[0])` – sashaaero Mar 21 '19 at 02:27
  • Note: python has `collection.Counter`, which makes these kind of problems simple, e.g. `sorted(Counter(sentence).items(), lambda letter: (letter[1], letter[0]))` – AChampion Mar 21 '19 at 02:39
  • @leonid that did not work I changed the sort=... to that comment and get this error code builtins.IndexError: string index out of range – Archer15 Mar 21 '19 at 02:44
  • @AChampion I can not use collection.counter, no library functions to accomplish the main goal of the problem. – Archer15 Mar 21 '19 at 02:45
  • @sashaaero did not work, – Archer15 Mar 21 '19 at 02:46
  • @Archer15 it works. Did you remove reverse as I did? – sashaaero Mar 21 '19 at 02:47

2 Answers2

1

This is pretty simple, you just need to use a different sorting key. Use a tuple of (frequency, letter) instead of just the frequency:

sort = sorted(dictionary.items(), key = lambda letter: (letter[1], letter[0]), reverse = True)

Note that there's a collections.Counter() in the standard library that makes a lot of this even simpler.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
  • `lambda letter: (letter[1], letter[0])` should be `lambda letter: (letter[1], -ord(letter[0]))` I think. Cause in your case letters are not sorted alphabetically. – sashaaero Mar 21 '19 at 02:40
  • cant use library functions, and this still does not print alphabetically ordered after numerically. – Archer15 Mar 21 '19 at 02:47
0

To sort first by of occurrence then alphabetically, you may change your sort key function to this:

sort = sorted(dictionary.items(), key = lambda letter:(-letter[1], letter[0]))
zhiqiang
  • 1
  • 1