5
\$\begingroup\$

I am participating in a challenge and one of the challenges was to write a script to sort a list of software versions (ex: 1.0, 1.3.2, 12, 1.3.0). Here is the my solution:

def answer(l):
     return sorted(l, key=lambda s: [int(i) for i in s.split('.')])
print(answer(eval(raw_input())))

In this code, I am essentially taking the list, and splitting each element by '.', converting them to integers, and then sorting the list. One thought is to use list comprehension to remove lambda altogether, but unsure how to achieve it.

\$\endgroup\$
  • \$\begingroup\$ What does "no modules" mean? You want to avoid any imports or are modules from the standard library fine? \$\endgroup\$ – 409_Conflict Jul 29 '18 at 12:21
  • \$\begingroup\$ I meant no imports. \$\endgroup\$ – user40929 Jul 29 '18 at 16:03
  • \$\begingroup\$ And what is the reason for such odd constraint? \$\endgroup\$ – 409_Conflict Jul 29 '18 at 19:22
  • \$\begingroup\$ It's a code challenge. \$\endgroup\$ – user40929 Jul 29 '18 at 23:15
0
\$\begingroup\$

The best way would be to use the distutils.StrictVersion as your sort key argument.

However, as you do not want to use imports, you may choose to copy the _cmp, __eq__, __le__ and other comparison methods as applicable, from the source file linked above. You'd also modify the parse method to use str.split instead of a regex matching.

I do not think you'd have to worry about pre-releases etc.


Why I'd go with distutils is because it has been tested since a long time. Writing your own version would be prone to errors, and edge cases.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.