Home > Enterprise >  Is this the right way to do stable sorting?
Is this the right way to do stable sorting?

Time:02-19

I'm tring to do this kattis problem (Sort of Sorting), but my code only gets past the first trial. I've tried with my own sample cases and I don't see why it shouldn't work. Can someone check my code and tell me what I'm doing wrong?

while True:
    terms = eval(input())
    if terms == 0:
        break
    x = []
    y = []
    for i in range(terms):
        x.append(input())
    for i in range(terms):
        z = x[i][:2]   ' '   str(i)
        y.append(z)
    y.sort()
    for i in range(terms):
        a,b = y[i].split()
        print(x[int(b)])
    print()

CodePudding user response:

The key argument to sort (which is already stable) does what you are looking for.

x.sort(key=lambda x: x[:2])

No need to build a temporary list y.

CodePudding user response:

Your code has several issues. I'll add a comment for each one.

while True:
    terms = int(input())  # Technically, eval works here, but be careful!
    # Don't call eval with user input, that's a huge security issue.
    # See https://en.wikipedia.org/wiki/Code_injection
    if terms == 0:
        break
    names = []  # A more meaningful name
    for i in range(terms):
        names.append(input())
    # You don't need the other list, it only causes problems for you.
    # Including that it makes the sorting unstable (`2 < 11`, but `"2" > "11"`)
    # Instead, use the key argument to sort or sorted:
    names.sort(key=lambda name: name[:2])  # Python sort is stable
    for name in names:
        # Without the extra list, you can simply print the list
        # without trying to extract the original index
        print(name)
    print()
  • Related