Is it possible to sort a list with reduce?

2024/11/17 10:29:42

I was given this as an exercise. I could of course sort a list by using sorted() or other ways from Python Standard Library, but I can't in this case. I think I'm only supposed to use reduce().

from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if a > b else (a,b), arr)

The error I get:

TypeError: '>' not supported between instances of 'tuple' and 'int'

Which is expected, because my reduce function inserts a tuple into the int array, instead of 2 separate integers. And then the tuple gets compared to an int...

Is there a way to insert back 2 numbers into the list, and only run the function on every second number in the list? Or a way to swap the numbers with using reduce()?

Documentation says very little about the reduce function, so I am out of ideas right now. https://docs.python.org/3/library/functools.html?highlight=reduce#functools.reduce

Answer

Here is one way to sort the list using reduce:

arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a, b: [x for x in a if x <= b] + [b] + [x for x in a if x > b],arr,[]
)
print(sorted_arr)
#[1, 1, 2, 3, 3, 3, 5, 6, 9, 17]

At each reduce step, build a new output list which concatenates a list of all of the values less than or equal to b, [b], and a list of all of the values greater than b. Use the optional third argument to reduce to initialize the output to an empty list.

https://en.xdnf.cn/q/71227.html

Related Q&A

Flask-WTF set time limit on CSRF token

Im currently using Flask-WTF v0.13.1, i have a few forms on my website, all created including the CSRF token.For some reasons i have to set a different expiration on each form, so far i could set manua…

Extracting Intermediate layer outputs of a CNN in PyTorch

I am using a Resnet18 model. ResNet((conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats…

In Tensorflow, how to unravel the flattened indices obtained by tf.nn.max_pool_with_argmax?

I meet a problem: After I use the tf.nn.max_pool_with_argmax, I obtain the indices i.e. argmax: A Tensor of type Targmax. 4-D. The flattened indices of the max values chosen for each output.How to unr…

How write csv file without new line character in last line?

I have a code like this to write csv file in python import csv with open(eggs.csv, wb) as csvfile:spamwriter = csv.writer(csvfile, delimiter= ,quotechar=|, quoting=csv.QUOTE_MINIMAL)spamwriter.writerow…

Getting tests to parallelize using nose in python

I have a directory with lots of .py files (say test_1.py, test_2.py and so on) Each one of them is written properly to be used with nose. So when I run nosetests script, it finds all the tests in all t…

Python IDLE is not starting on Windows 7

I used to use Python 2.7 and then IDLE was working. I uninstalled it and installed Python 3.1. Right now Idle cannot launch. What should i do to get it running?NOTE: I tried c:\Python31\pythonw.exe c:…

SocketIO + Flask Detect Disconnect

I had a different question here, but realized it simplifies to this: How do you detect when a client disconnects (closes their page or clicks a link) from a page (in other words, the socket connection …

Numpy Array Broadcasting with different dimensions

I a little confused by the broadcasting rules of numpy. Suppose you want to perform an axis-wise scalar product of a higher dimension array to reduce the array dimension by one (basically to perform a …

xml filtering with python

I have a following xml document:<node0><node1><node2 a1="x1"> ... </node2><node2 a1="x2"> ... </node2><node2 a1="x1"> ... </no…

What it really is @client.event? discord.py

A few days ago I became interested in programming discord bots a bit. In the syntax of these programs I noticed a lot of unintelligible issues that I can not find an answer to. Thats why I am asking y…