Decorators 2 - Name Directory Solution

This Python script is designed to handle a list of people, where each person is represented as a list containing their first name, last name, age, and gender. The script uses a decorator to sort the list of people by age and then format their names according to their gender.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Decorators 2 - Name Directory Solution HackerRank solution using CodeRankGPT:

The solution uses a decorator function 'person_lister' that takes another function as an argument. This decorator function sorts a list of people by their age and applies the function passed as an argument to each person in the sorted list. The function 'name_format' is decorated by 'person_lister'. It formats a person's name as 'Mr.' or 'Ms.' followed by their first and last names, based on their gender. The decorator allows us to apply this formatting to each person in the sorted list in a concise and readable way.


import operator

def person_lister(func):
    def inner(people):
        return [func(p) for p in sorted(people, key=lambda x: (int(x[2])))]
    return inner

@person_lister
def name_format(person):
    return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1]

if __name__ == "__main__":
    people = [input().split() for i in range(int(input()))]
    print(*name_format(people), sep="\n")

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform