8man
8man

Reputation: 3

How to sort a string?

task is : Could you make a program that

makes this string uppercase gives it sorted in alphabetical order by last name. When the last names are the same, sort them by first name. Last name and first name of a guest come in the result between parentheses separated by a comma.

what i did:

def meeting(s):
    res=''
    for i in s.split(';'):
        s1 = i.split(':')[::-1]
        res += '(' + ', '.join(s1) + ')'
    return  res.upper()

input:

testing("Alexis:Wahl;John:Bell;Victoria:Schwarz;Abba:Dorny;Grace:Meta;Ann:Arno;Madison:STAN;Alex:Cornwell;Lewis:Kern;Megan:Stan;Alex:Korn") 

this what i got:

(WAHL, ALEXIS)(BELL, JOHN)(SCHWARZ, VICTORIA)(DORNY, ABBA)(META, GRACE)(ARNO, ANN)(STAN, MADISON)(CORNWELL, ALEX)(KERN, LEWIS)(STAN, MEGAN)(KORN, ALEX)

and this what i need:

(ARNO, ANN)(BELL, JOHN)(CORNWELL, ALEX)(DORNY, ABBA)(KERN, LEWIS)(KORN, ALEX) (META, GRACE)(SCHWARZ, VICTORIA)(STAN, MADISON)(STAN, MEGAN)(WAHL, ALEXIS)

How to sort it as needed?

Upvotes: 0

Views: 204

Answers (2)

Phydeaux
Phydeaux

Reputation: 2855

Since you put the last name first in the output, you can do the formatting first and then just sort alphabetically:

def meeting(names):
    formatted_names_list = ["({}, {})".format(*reversed(name.split(":"))).upper()
                            for name in names.split(";")]

    return "".join(sorted(formatted_names_list))

Upvotes: 1

Eran
Eran

Reputation: 2424

What you want is to call the sort function on the list and to specify the way it sorts. You s1 list contains tuples of two items each. And you seem to want your sorting to be first by the first item, and a secondary sort (breaking ties) on the second item. In order to achieve that you should first sort on the secondary condition and then on the primary. This is because python's sort is "stable" which means that in each sort operation ties are kept in the order that they started with. To give the condition to the sort function you specify a lambda as the key argument, the lambda has one argument (will be each tuple in the list) and returns the property on which you want to sort (the specific item in the tuple).

Here is an example:

def meeting(s):
    res=''
    for i in s.split(';'):
        s1 = i.split(':')[::-1]
        s1.sort(key=lambda x: x[1])  # sort according to secondary condition
        s1.sort(key=lambda x: x[0])  # re-sort with primary condition 
        res += '(' + ', '.join(s1) + ')'
    return res.upper()

Upvotes: 0

Related Questions