Printing name of second lowest mark scorer in a nested list and arranging in alphabetical order in Python

99封情书 提交于 2020-06-29 05:13:01

问题


    if __name__ == '__main__':
    arr = []
        for _ in range(int(input())):
            name = input()
            arr.append(name)
            score = float(input())
            arr.append(score)

        array = [arr[i:i+2] for i in range(0, len(arr), 2)]
        marks = []
        for j in range(0, len(array)):
            marks.append(array[j][1])
        marks = list(map(float, marks))
        marks.sort()
        seclow = marks[1]
        for k in range(0, len(array)):
            if (seclow == float(array[k][1])):
                print(array[k][0])
**SAMPLE INPUT:**

    5
    Harry
    37.21
    Berry
    37.21
    Tina
    37.2
    Akriti
    41
    Harsh
    39
**EXPECTED OUTPUT:**

    BERRY
    HARRY

**MY OUTPUT:**

    HARRY
    BERRY

The only problem is ordering the names with the lowest scores in alphabetical order. I should use lists to pass the test case. So, what changes should be done to the code?


回答1:


Not using any imports and in less code, it can be done this way. I also put it into a function just to make it a little cleaner and so you can reuse it elsewhere if needed.

def main():
    scores_dict = {}
    for _ in range(int(input())):
        name, score = input(), float(input())

        if score not in scores_dict:
            scores_dict[score] = []
        scores_dict[score].append(name)

    # Delete the min score key and names so that we can grab the second min
    del scores_dict[min(scores_dict.keys())]

    # Get new min score.
    min_score = min(scores_dict.keys())

    # Sort new min score.
    scores_dict[min_score].sort()
    # Print each name in results
    [print(i) for i in scores_dict[min_score]]

if __name__ == '__main__':
    main()




回答2:


Check via here: https://ide.geeksforgeeks.org/fMD7OgxYC7

Instead of defining list. Store it in a dictionary. This will give you space-optimized solution. Then sort dictionary by value. add the names having the score in a dictionary.

Try:

import collections
if __name__ == '__main__':
    arr = {}
    for _ in range(int(input())):
        name = input()
        score = float(input())
        arr[name] = score

    dd = collections.defaultdict(list)

    for k,v in arr.items():
        dd[v].append(k)

    x = sorted(dd.items())
    sec_low = sorted(x[1][1])
    for i in sec_low:
        print(i)

Input:

5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

Output:

Berry
Harry

x:

[(37.2, ['Tina']),
 (37.21, ['Harry', 'Berry']),
 (39.0, ['Harsh']),
 (41.0, ['Akriti'])]



回答3:


Handles duplicate lowest and duplicate second lowest.

Sample input: {"hri":6.2,"dav":1.1,"asv":1.1,"wrs":12.3,"dup":6.2,"awe":43.2,"asw":22.2,"asd":6.2}

Output: ['asd', 'dup', 'hri'] can be printed joining to "\n"

def lowest_scores(names_scores):
    
        lowest_score=min(names_scores.values())
        
        lowscorers=[]
    
        low_scorer_dict = { k : v for k,v in names_scores.items() if v != lowest_score}
        
        second_lowest_score = min(low_scorer_dict.values())
    
        for k,v in low_scorer_dict.items():
            if v == second_lowest_score:
                lowscorers.append(k)
            
        return sorted(lowscorers)


来源:https://stackoverflow.com/questions/60828477/printing-name-of-second-lowest-mark-scorer-in-a-nested-list-and-arranging-in-alp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!