3 ms·
If you change it slightly you can make it more readable: def is_unique(elements): unique_elements = set(elements) has_only_unique_elements = l
by 29athrowaway 5y ago
If you change it slightly you can make it more readable:
def is_unique(elements):
unique_elements = set(elements)
has_only_unique_elements = len(unique_elements) == len(elements)
return has_only_unique_elements
The problem was using identifiers like "l", and trying to make everything a one-liner.
Adding a docstring or comment can help too.
Is that still "clever code" after these few changes? I would say no.
- aldanor 5y agoAnyone who's written a fair share of Python can immediately see "len(set(l)) == len(l)" as "no duplicate elements", this is such a standard way to check for duplicates in Python that the chances are you've see this expression in this exact form dozens if not hundreds of times already. Agreed with "l" identifier and docstring/comment. You'd probably write it like this if you want it to look nice: from typing import Iterable, Any def is_unique(elements: Iterable[Any]) -> bool: "Returns True if the argument has no duplicate elements." elements = list(elements) return len(elements) == len(set(elements))
- 29athrowaway 5y agoI know Python but my Python is not the most Pythonic. The typing does make it more readable, but the "anyone who's written a fair share of Python can immediately see..." argument doesn't resonate with me. Naming boolean expressions saves time.
- koningrobot 5y agoThey did name the boolean expression; they named it `is_unique`. It's a poor name, but that's a different argument.
- bidirectional 5y agoIt blows my mind that anyone would consider your refactoring more readable. I don't think the example in OP suffers from readability issues at all, nor did the article suggest that. If anything it was just good, simple, 'clever' code.
- 29athrowaway 5y agoNamed boolean expressions, when used properly, make the effort of reading the actual expression optional.