0

Given a string, you have to find the first n most frequent characters in it. If there are two letters with the same frequency, then the alphabetically earlier value should be picked first:

string=  "aabbccc"
n =2
list = []
#write your code here
char_dict = {}

for char in string:
    if char not in char_dict:
        char_dict[char] = 1
    else:
        char_dict[char] += 1


sorted_dict=sorted(char_dict.items(), key=lambda x: (x[1],x[0]))

sorted_dict = sorted_dict[-2:]
for key, value in sorted_dict:
    list.append(key)
print(list)

My output is ['b', 'c'] but it should actually be c and a.

Adrian Mole
  • 43,040
  • 110
  • 45
  • 72
rinki kumari
  • 9
  • 1
  • 4

4 Answers4

5

The problem is with the sorting. You need to sort by two fields in different directions (1 ascending and 1 descending). Change the sorted_dict 2 lines to:

sorted_dict = sorted(char_dict.items(), key=lambda x: (-x[1], x[0]))
sorted_dict = sorted_dict[:n]

btw: Avoid using python's keywords (such as list) as variable names. Name it myList or something similar.

Aryerez
  • 3,138
  • 2
  • 7
  • 16
2

Below is one of the perfect solution for your problem(with less code)

string=input()
n=int(input())
import collections
out=[collections.Counter(string).most_common(i+1)[i][0] for i in range(n)]
out.sort()
print(out)
Sunil
  • 21
  • 1
1

I added the print outputs after the statement. The code should be selfdescripting.

from collections import defaultdict

string=  "aabbccc"
n = 2

result = defaultdict(int)
for char in string:
    result[char] += 1
print(result)  # defaultdict(<class 'int'>, {'b': 2, 'a': 2, 'c': 3})

ordered_result = sorted(result.items(), key=lambda x: (-x[1], x[0]))
print(ordered_result)  # [('c', 3), ('a', 2), ('b', 2)]

ordered_list = [x[0] for x in ordered_result]
print(ordered_list[:n])  # ['c', 'a']
Frank
  • 1,543
  • 10
  • 24
0
def char_frequency(string,n):
  letter_freq = dict()
  for letter in string:
    if letter not in letter_freq.keys():
      letter_freq[letter] = 1
    else:
      letter_freq[letter] += 1

  list_of_tuples = sorted(letter_freq.items(), key=lambda x: (-x[1],x[0]))[:n]
  print(list_of_tuples)
  final_list = []
  for tup in list_of_tuples:
    final_list.append(tup[0])
  return(sorted(final_list))

print(char_frequency("aabbccc",2))
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 24 '21 at 02:37