Given 2 strings I want to return a string that is the result of concatenating the smaller string plus the larger string and plus the smaller string.
def combo_string(a, b):
mini = min(a, b)
maxi = max(a, b)
return mini + maxi + mini
I tried the function and it returns a string where the largest string is first concatenated with the smallest string and concatenated with the largest.
What happens is that as much
max()
as theymin()
return the maximum or minimum of the indicated strings according to alphabetical order, but it has nothing to do with their lengths.Example:
To do what you are looking for, you could solve it this way:
We use a ternary operator asking for the length of each string. so we assign the corresponding variable.
min
andmax
they don't take into account the length of the strings, they take into account the lexicographical order. In any case, if you want to use this approach, you should usemax
ymin
on the output oflen
, which you can do using the argumentkey
:or you can use directly
sorted
:key
allows to indicate amin
,max
,sorted
andlist.sort
what must be taken into account to order the items, in this case when ordering it uses the return oflen(cad)
, that is, the length of each string.String concatenation is inefficient due to its immutability (in each concatenation a new string has to be created which then has to be eliminated by the GC), whenever you concatenate more than two consider uses
str.join
or string literals formatted in Python >= 3.6If both strings happen to be the same length, just keep the initial order:
Either way, the most efficient way for the concrete result you want in this case is to use a simple
if
:or directly: