-1

I have a coding project and here is my code

from operator import itemgetter 
# 1. Get input
# 2. Split each letter and number
# 3. Find the 5 most frequent numbers
# 4. Find the letter or number and print the answers
countcount = 0

N = 5
# Overview code
input123 = str(input('Please enter your letters \n')).replace(" ", "")
test_list = str({i :input123.count(i) for i in set(input123)})

# Get Top N elements from Records 
# Using sorted() + itemgetter() 
res = sorted(test_list, key = itemgetter(0), reverse = True)[:N] 
  
# printing result 
print("The top N records are : " + str(res))
print(str(res))

As you can see, I want to enter a random string and get the top 5 letter/numbers. Right now if I enter qqqqqqwwwwweeeerrrtty, 2 of the answers would be { and } while the rest would be either q,w,e,r,t or y. Am I using itemgetter wrongly?

MS1
  • 13
  • 5

2 Answers2

1

itemgetter is not the issue. You shouldn't convert test_list into a str (this is what introduces the {}); instead keep it as a dict. Then refer to How do I sort a dictionary by value? to sort the dict as you wished.

Demi-Lune
  • 1,868
  • 2
  • 15
  • 26
0

Another datatype that might be more suitable for counting e.g. characters is the Counter which has a built-in most_common method.

from collections import Counter
_input = input("Please enter your letters: ").replace(" ", "")
counter = Counter(_input)
print(counter.most_common(5))
# Or the below row in case you only want the character and not the tuple with char + num of occurences.
# print([tup[0] for tup in counter.most_common(5))

Given the input qqqqqqwwwwweeeerrrttyyou would get the output ['q','w','e','r','t'] or [('q', 6), ('w', 5), ('e', 4), ('r', 3), ('t', 2)]depending on which of the two print options you select in the example above.

tbjorch
  • 1,544
  • 1
  • 8
  • 21