I am learning python and would like to know if there is a pythonic way of doing this. Of course I can do an
if len(a) > len(b) :
(x,y) = (b,a)
and so on. But this seems a bit verbose. Is there a more beautiful way to do this in python?
I am learning python and would like to know if there is a pythonic way of doing this. Of course I can do an
if len(a) > len(b) :
(x,y) = (b,a)
and so on. But this seems a bit verbose. Is there a more beautiful way to do this in python?
Sorting seems a bit overkill. You can do it in one line just with if.
x,y = (a,b) if len(a) < len(b) else (b,a)
x = min(a, b, key=len)
y = max(a, b, key=len)
Repetition, but intention is clear.
Removed parentheses that makes tuples out of a and b since min and max takes in variable number of arguments.
Use min(n1, n2, n3, ...)
>>> n1 = "abcdefghijkl"
>>> n2 = "abc"
>>> min((n1,n2), key=len)
'abc'
>>> max((n1,n2), key=len)
'abcdefghijkl'
You can use sequence unpacking with min / max. This is still O(n) complexity, albeit a 2-pass solution, which doesn't involve creating an intermediary list or tuple of strings.
a = 'hello'
b = 'test'
x, y = (func(a, b, key=len) for func in (min, max))
print(x, y, sep='\n')
# test
# hello
Here's a functional version:
from operator import methodcaller
x, y = map(methodcaller('__call__', a, b, key=len), (min, max))
The question seems really opinion-based, and for this reason I think we should define beautiful referring to the Zen of Python, in particular:
Flat is better than nested.
Sparse is better than dense.
Readability counts.
For these reasons, I think that your approach:
if len(a) > len(b) :
(x,y) = (b,a)
else:
(x,y) = (a,b)
is the best one.
Just a demo how dict can also be used
Solution 1:
a = [3]
b = [2,3 ]
_bool = len(a)<len(b)
d = { True : a, False : b}
x = d[_bool]
y = d[not _bool]
print(x, y)
Using Lists:
Solution 2:
x, y = [[a, b], [b, a]][len(a) > len(b)]
Although my preferred approach is
x, y = sorted([a, b], key=len)