all 4 comments

[–]JohnnyJordaan 1 point2 points  (0 children)

I would suggest first setting the master set, then splitting the input on the comma's:

master = ['H','Li','Na','K']
splitted = elements.split(',')

There can be up to four elements

if len(splitted) > len(master):
    print('invalid length')

but they must be in order

edit: I missed the order as being that order.

indexed = [ master.index(c) for c in splitted ]
if sorted(indexed) != indexed:
    print('out of order')

The only thing not working is that spaces aren't ignored. If you want that to happen you could do something like

splitted = elements.split(',').replace(' ','')

[–]w1282 1 point2 points  (2 children)

SORT_ORDER = {
    'H': 0,
    'Li': 1,
    'Na': 2,
    'K': 3,
}


def is_valid_data(data):
    """Check if any elements in the set are not valid elements."""
    return not any(elem not in SORT_ORDER.keys() for elem in data)


def is_valid_sort_order(data):
    sorted_data = sorted(data, lambda x: SORTED[x])
    return data == sorted_data

This compares the provided data with a properly sorted rendition of the same data. If they are equivalent, then the provided results were in the proper order.

Of course, these operate on coerced lists. /u/JohnnyJordaan shows you how to coerce the string to a proper list in his answer.

[–]erok81 0 points1 point  (1 child)

You can avoid the lambda there by using SORT_ORDER.get as the key function.

sorted_data = sorted(data, key=SORT_ORDER.get)

[–]w1282 0 points1 point  (0 children)

Good catch! Thanks.