Home > Software engineering >  List of Starters in dictionaries
List of Starters in dictionaries

Time:01-24

in the given method called solve which takes as parameter a list of strings called items.

You have to print the list of items for each alphabet. Print in sorted order of alphabets.

Example Input:

noodles, rice, banan, sweets, ramen, souffle, apricot, apple, bread

Output:

a : apple apricot

b : banana bread

n : noodles

r : ramen rice

s : souffle sweets

    import collections 
    def solve(items):
          result = {}
          for word in items:
              char = word[0]
              if char in result:
              result[char].append(word)
              else:
             result[char] = [word]
         od = collections.OrderedDict(sorted(result.items()))
         for key, value in od.items():
                    print ("%s : %s"%(key,value))

but, im getting it in brakets...! not like a desired output...

CodePudding user response:

You are not performing any comparisons to find the maxEnglish or the maxTotalMarks. The reason print('Max Marks:',d['name']) is printing the correct result is because Dwight is the last entry in the Ordered Dictionary and you are printing the last item's name.

One of the ways you could tackle this question is by keeping variables that keep track of the maximum scores and as you iterate through the dictionary, you can compare against these stored value to determine if the current value that you are iterating is greater or lesser than all the values that you have seen so far. Something like this:

def solve(stats):
    maxEnglishMarks = -1
    maxTotalMarks = -1
    maxEnglishStudentName = maxTotalStudentName = None
    
    for stat in stats:
        totalMarks = sum([i for i in stat.values() if str(i).isnumeric() == True])
        if totalMarks > maxTotalMarks:
            maxTotalStudentName = stat['name']
            maxTotalMarks = totalMarks
        if stat['English'] > maxEnglishMarks:
            maxEnglishStudentName = stat['name']
            maxEnglishMarks = stat['English']
    print('Max English:', maxEnglishStudentName)
    print('Max Marks:', maxTotalStudentName)
            
    
    
stats = [
    {'name': 'Jim', 'English': 92, 'Math': 80, 'Physics': 70},
    {'name': 'Pam', 'French': 72, 'English': 80, 'Biology': 65},
    {'name': 'Dwight', 'Farming': 95, 'English': 85, 'Chemistry': 97}
]

solve(stats)

CodePudding user response:

Alternatively you can try to leverage Python collections.defaultdict as this way:

from collections import defaultdict
from pprint import pprint

inputs = "noodles, rice, banan, sweets, ramen, souffle, apricot, apple, bread"

groups = defaultdict(list)

lst = inputs.split(', ')
#print(lst)

for item in lst:
    groups[item[0]].append(item)

for k, val in sorted(groups.items()):
    print(k, ": ", *val)          # *val to expand the list content
    
#pprint(groups)

Output: # you could convert this to the function easily as an exercise...

a :  apricot apple
b :  banan bread
n :  noodles
r :  rice ramen
s :  sweets souffle
  •  Tags:  
  • Related