Python Forum
Descending order unique squares
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Descending order unique squares
#1
Good day, Dear Pythonistas

I have the following problem: Given a list, we should write a function that returns sorted in descending order unique squares of numbers contained in this list

I have got the solution in the following way, it works correctly:
def squares_list(l):
    for elem in l:
        empty_list.extend(elem)
    new_list=list(set(empty_list))
    new_list.sort(reverse=True)
    squares=[i**2 for i in new_list]
    return squares
print(squares_list([[1, 2], [3], [4], [3, 1]]))
Could you, please, suggest, how I could write this code or the solution in the shortest possible optimal way (a smaller number of characters)?
Reply
#2
Search for a short way to flatten the list. Maybe itertools.chain?

Do not use variables to save intermediate results. Chain operations together using return values
    return [i**2 for i in new_list]
    # instead of
    squares=[i**2 for i in new_list]
    return squares
Use sorted instead of sort.
sorted_unique_list=sorted(set(unsorted_list))
I can write your function as a 1 liner, and I didn't have to be clever. For a one liner it doesn't look too bad
Reply
#3
Thank you very much) By now it looks like this:
import itertools
def process(l):
    return [i**2 for i in sorted(set(list(itertools.chain(*l))))[::-1]]
Reply
#4
Why do you need the call to list there?
OmegaRed94 likes this post
Reply
#5
Leave out the list() call. Not needed. Have sorted reverse the order
OmegaRed94 likes this post
Reply
#6
(Sep-26-2021, 09:00 AM)deanhystad Wrote: Leave out the list() call. Not needed. Have sorted reverse the order

Thanks again
Reply
#7
If the nesting of all the function calls bothers you, you can probably flatten it out with thread_first or thread_last from the third-party Toolz library.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  a generator that computes squares of first 20 natural numbers mdshamim06 1 8,899 Oct-01-2019, 10:38 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020