Descending order unique squares - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Descending order unique squares (/thread-35063.html) |
Descending order unique squares - OmegaRed94 - Sep-26-2021 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)? RE: Descending order unique squares - deanhystad - Sep-26-2021 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 squaresUse 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 RE: Descending order unique squares - OmegaRed94 - Sep-26-2021 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]] RE: Descending order unique squares - ndc85430 - Sep-26-2021 Why do you need the call to list there?
RE: Descending order unique squares - deanhystad - Sep-26-2021 Leave out the list() call. Not needed. Have sorted reverse the order RE: Descending order unique squares - OmegaRed94 - Sep-26-2021 (Sep-26-2021, 09:00 AM)deanhystad Wrote: Leave out the list() call. Not needed. Have sorted reverse the order Thanks again RE: Descending order unique squares - ndc85430 - Sep-26-2021 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.
|