-1

I'm starting with a list of strings. Each element contains a name and a Roman numeral. I want to sort this list alphabetically by name, and then by the Roman numeral.

I only managed to create a list with [name, numeral] strings, so far:

names = ['Louis IX', 'Louis VIII', 'Maria III', 'Oscar IV', 'Adams XXX', 'Anuar III', 'Maria III', 'Oscar V']

def sortRoman(names):
    names_separated = []
    age_separated = []
    for i in range(len(names)):
        separated = names[i].split()
        for j in range(len(separated)):
            if j % 2 == 0:
                names_separated.append(separated[j])
            else:
                age_separated.append(separated[j])

    list_full_ordered = zip(names_separated, age_separated)
    return list(sorted(list_full_ordered))


if __name__ == "__main__":
    print(sortRoman(names))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I can use any approach just considering that the entry comes in a list of text strings and the output must be sorted first by name alphabetically and then by Roman hierarchy @asked 2 – Nelson Acosta Nov 06 '19 at 13:04
  • 1
    You want to break down the problem. You need to a) extract the roman numeral, then b) convert that numeral to an integer (see the duplicate), then sort your input list by `(name, numeric_value)` tuples, see the other duplicate. – Martijn Pieters Nov 06 '19 at 13:32
  • Basically, you'd use a separate function to convert from numeral to integer, and use a sort key function that takes any *one* string in the list, does the splitting and returns the name and converted numeral: `def sortkey(s):`, `name, numeral = s.split()`, `return (name, numeral_to_int(numeral))` and use that as the `key` argument to `sorted()`: `sorted(names, key=sortkey)`. – Martijn Pieters Nov 06 '19 at 13:34

1 Answers1

2

This is one approach using custom module roman

Ex:

import roman

def foo(x):
    n, r = x.split()
    return n, roman.fromRoman(r)

names = ['Louis IX', 'Louis VIII', 'Maria III', 'Oscar IV', 'Adams XXX', 'Anuar III', 'Maria III', 'Oscar V']
names = sorted(set(names), key=foo)

print(names)

Output:

['Adams XXX', 'Anuar III', 'Louis VIII', 'Louis IX', 'Maria III', 'Oscar IV', 'Oscar V']
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • I think it's a great solution, if I also want to eliminate duplicates? – Nelson Acosta Nov 06 '19 at 13:11
  • use `set()` --> `names = sorted([i.split() for i in set(names)], key=lambda x: (x[0], roman.fromRoman(x[-1])))` – Rakesh Nov 06 '19 at 13:13
  • 1
    thanks, any other approach to achieve it without a library? This problem is a case to practice problem solving so I would like to know another approach @Rakesh – Nelson Acosta Nov 06 '19 at 13:20