3 ms·
It's also not performing the numeric sort ('-n'), which is arguably the hardest part because it's not a Python built-in. A bad example all around. Here's my at
by BoppreH 4y ago
It's also not performing the numeric sort ('-n'), which is arguably the hardest part because it's not a Python built-in. A bad example all around.
Here's my attempt[1]:
import re
lines = list(set(line for line in open('beef.txt') if 'lasagna' in line))
lines.sort(key=lambda line: int(re.match('\d*', line)[0] or 0))
for line in lines: print(line, end='')
Python is especially bad at this task for a number of reasons:
- Iterating over the lines yields strings ending with newlines. If you naively loop and print the sorted lines, `print` will add a second newline, resulting in every other line being empty. Hence the `end=''`.
- Python's str has many helper functions, but none for numeric sort, so you need an import, a regex, and a fallback value.
- It's very imperative with a big mutation in the middle. Using `sorted(lines, key=...)` and `print(''.join(lines))` would be simpler and safer, but each would double the memory usage for large inputs.
- Filters using list comprehensions ('x for x in y if z in x') are idiomatic and readable but very verbose.
- The concepts are a lot more complicated. Here we have file handles, magic iterators, first-class-functions, sets, generators, lists, keyword arguments, regexes, overloaded indexes, etc. A beginner would blindly copy and run, and have no chance to fix any issues that appear.
- Because Python has almost no static analysis (undefined names are runtime errors!), you'll have to find most errors by running your code. For a quick shell script this usually mean running over the real inputs, giving a horribly slow edit-compile-run loop and be potentially dangerous.
[1]: https://gist.github.com/boppreh/3cf5489da92d85f11e152739320d147e https://gist.github.com/boppreh/3cf5489da92d85f11e152739320d...