Skip to main content
added 127 characters in body
Source Link
mhawke
  • 87.5k
  • 10
  • 122
  • 142

Why don't you just use a collections.Countercollections.Counter? For example:

from collections import Counter from operator import itemgetter word = input('Enter a word: ') c = Counter(word) letter_arr, num_arr = zip(*sorted(c.items(), key=itemgetter(1,0))) print(letter_arr) print(num_arr) 

Note the use of sorted() to sort by increasing frequency. itemgetter() is used to reverse the sort order so that the sort is performed first on the frequency, and then on the letter. The sorted frequencies are then separated using zip() on the unpacked list.

Demo

 Enter a word: Hello ('H', 'e', 'o', 'l') (1, 1, 1, 2) 

The results are tuples, but you can convert to lists if you want with list(letter_arr) and list(num_arr).

Why don't you just use a collections.Counter? For example:

from collections import Counter from operator import itemgetter word = input('Enter a word: ') c = Counter(word) letter_arr, num_arr = zip(*sorted(c.items(), key=itemgetter(1,0))) print(letter_arr) print(num_arr) 

Note the use of sorted() to sort by increasing frequency. The sorted frequencies are then separated using zip() on the unpacked list.

Demo

 Enter a word: Hello ('H', 'e', 'o', 'l') (1, 1, 1, 2) 

The results are tuples, but you can convert to lists if you want with list(letter_arr).

Why don't you just use a collections.Counter? For example:

from collections import Counter from operator import itemgetter word = input('Enter a word: ') c = Counter(word) letter_arr, num_arr = zip(*sorted(c.items(), key=itemgetter(1,0))) print(letter_arr) print(num_arr) 

Note the use of sorted() to sort by increasing frequency. itemgetter() is used to reverse the sort order so that the sort is performed first on the frequency, and then on the letter. The sorted frequencies are then separated using zip() on the unpacked list.

Demo

 Enter a word: Hello ('H', 'e', 'o', 'l') (1, 1, 1, 2) 

The results are tuples, but you can convert to lists if you want with list(letter_arr) and list(num_arr).

Source Link
mhawke
  • 87.5k
  • 10
  • 122
  • 142

Why don't you just use a collections.Counter? For example:

from collections import Counter from operator import itemgetter word = input('Enter a word: ') c = Counter(word) letter_arr, num_arr = zip(*sorted(c.items(), key=itemgetter(1,0))) print(letter_arr) print(num_arr) 

Note the use of sorted() to sort by increasing frequency. The sorted frequencies are then separated using zip() on the unpacked list.

Demo

 Enter a word: Hello ('H', 'e', 'o', 'l') (1, 1, 1, 2) 

The results are tuples, but you can convert to lists if you want with list(letter_arr).