Remove the brackets from the Sorted() function

Asked

Viewed 170 times

4

I was creating a quadratic function calculator and wanted to lay down roots in the ascending order. Searching, I arrived at the function sorted().

raiz1 = round((-b + math.sqrt(delta)) / (2 * a), 2)
raiz2 = round((-b - math.sqrt(delta)) / (2 * a), 2)

raizes = [raiz1, raiz2]

if delta > 0:
    print(f"A função tem duas raízes reais, que são: {sorted(raizes, key=int)}.")

The result of this is that I’m going to have the roots in brackets, rather than parentheses, as is the pattern. I know this is no big deal, but I think in the future there will be situations where I don’t want the numbers in brackets, so I’d like to know if there’s any way to delete them.

3 answers

4


sorted returns a list, and when you print a list, the elements are shown in square brackets, so it’s not that "sorted returns the brackets", is that the brackets are part of the textual representation of a list, that is, the way it was chosen to display a list in text form (but the brackets themselves are not part of the list, as it only has the values).

If you do not want the brackets shown, then do not print the list directly. An alternative is to turn the list into a single string, using join, and then you put the parentheses around her:

print(f"A função tem duas raízes reais, que são: ({', '.join(map(str, sorted(raizes, key=int)))}).")

Note the parentheses before and after { and }: they will be around the string generated by join. In the case, join will put the values separated by , (comma and space - and you can trade in whatever you want).

Or, to make it a little clearer what’s going on:

raizes_texto = ', '.join(map(str, sorted(raizes, key=int)))
print(f"A função tem duas raízes reais, que são: ({raizes_texto}).")

In this case, I also used map along with str to transform the values into strings, since the join error if elements are not strings.


I guess it doesn’t make much sense to use key=int, for then you will be ordering the roots by their entire values. So if you have:

raizes = [2.5, 2.4]

By turning them into int, both shall be equal to 2, then they will not change order, because the documentation says that the ordering is stable, that is, it does not change the order of 2 elements if they are considered equal. Therefore, as you have done, the roots will not be ordered if they have values with decimals. If you want to order them, just use sorted and ready:

raizes_texto = ', '.join(map(str, sorted(raizes)))
print(f"A função tem duas raízes reais, que são: ({raizes_texto}).")

Another alternative is to turn the list into a tuple, because tuples, when printed, show the elements in parentheses:

print(f"A função tem duas raízes reais, que são: {tuple(sorted(raizes))}.")

Although this I find kind of "gambiarra" (as well as solutions that make replace of the brackets, or anything else that depends on the specific implementation of how the list is printed). A replace may seem "innocent" and even work for this specific case, but you just have a list in which one of the elements is a string whose text contains a square bracket, to stop everything from working (or a list of lists as the internal lists are also printed with brackets and these will be removed improperly, see an example).

Anyway, if you want a specific format, then build the string explicitly, according to what you want.

3

There are several ways to do this.

You can create a variable that receives the return of the function sorted and then access the array indexes:

raizes = [10, 5]

raizesParaExibir = sorted(raizes)

print(f"A função tem duas raízes reais, que são: {raizesParaExibir[0]} e {raizesParaExibir[1]}.")

Following the same logic, you can sort the list raizes with the method sort and then access the indexes:

raizes = [10, 5]

raizes.sort()

print(f"A função tem duas raízes reais, que são: {raizes[0]} e {raizes[1]}.")

We can turn the list into a string and remove the brackets with the method strip:

raizes = [10, 5]

print(f"A função tem duas raízes reais, que são: {str(sorted(raizes)).strip('[]')}.")

Again, following this logic, we can remove the brackets using the method replace:

raizes = [10, 5]

print(f"A função tem duas raízes reais, que são: {str(sorted(raizes)).replace('[', '').replace(']', '')}.")

As a last example, we can use the method join of the string together with the function map:

raizes = [10, 5]

print(f"A função tem duas raízes reais, que são: {', '.join(map(lambda x: str(x), sorted(raizes)))}.")

See all these examples online: https://repl.it/repls/SeagreenGiddyBruteforceprogramming

1

You can use the function join

print(f"A função tem duas raízes reais, que são: {','.join(str(v) for v in sorted(raizes, key=int))}.")

In the above change, first the list returned by sorted has its values converted into strings. Then the function join concatenates the values of iterable resultant.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.