Arrange Names

Arrange Names

Teachers of Indian Academy Public School collect the names of those students who are going to participate in the Mathematics exhibition, that is to be held in a week’s time.  They have collected all the names and now, they want to store all the names into a system, in the descending order of the length of the names.  This means, the longest name should get stored first, followed by the name that is shorter than the previous, and so on.   Can you help the teachers to perform this task easily by creating a program in Python?

Note:   The number of names specified must be positive, else the program should display the message “Invalid Input” terminate the program. 

Input format:

Input consists of an integer that corresponds to the number of names followed by the names

Output Format:

Print the name list sorted by the names’ length, if name length are equal sort based on alphabetical order in descending order as shown in the sample input and output.

Sample Input and Output 1:

Enter the number of names:
5
Enter the names:
Safiq
Manish
Arun
Sanisha
Kumar

The sorted name list is:
Sanisha
Manish
Safiq
Kumar
Arun

Sample Input and Output 2:Enter the number of names:

-1

Invalid Input

Sample Input and Output 3:
Enter the number of names :3
Enter the names:
Veena
Jeena
Meena

The sorted name list is:
Veena
Meena
Jeena

Code :-

n=int(input("Enter the number of names:\n"))
l=[]
if n>0:
    print("Enter the names:")
    for i in range(n):
        l.append(input())
    print("The sorted name list is:")
    l.sort(key=len,reverse=True)
    for i in range(n-1):
        if len(l[i])==len(l[i+1]) and l[i]<l[i+1]:
            l[i],l[i+1]=l[i+1],l[i]
        continue
    for i in l:
        print(i)
else:
    print("Invalid Input")
    

Leave a Comment

Your email address will not be published. Required fields are marked *

x