Note that there are some explanatory texts on larger screens.

plurals
  1. POSort a list based on a given distribution
    text
    copied!<p>Answering one <a href="https://stackoverflow.com/a/14281624/977038">Question</a>, I ended up with a problem that I believe was a circumlocution way of solving which could have been done in a better way, but I was clueless</p> <p>There are two list</p> <pre><code>percent = [0.23, 0.27, 0.4, 0.1] optimal_partition = [3, 2, 2, 1] </code></pre> <p>optimal_partition, is one of the integer partition of the number 8 into 4 parts</p> <p>I would like to sort <code>optimal_partition</code>, in a manner which matches the percentage distribution to as closest as possible which would mean, the individual partition should match the percent magnitude as closest as possible</p> <p>So <code>3 -&gt; 0.4</code>, <code>2 -&gt; 0.27</code> and <code>0.23</code> and <code>1 -&gt; 0.1</code></p> <p>So the final result should be</p> <pre><code>[2, 2, 3, 1] </code></pre> <p>The way I ended up solving this was</p> <pre><code>&gt;&gt;&gt; percent = [0.23, 0.27, 0.4, 0.1] &gt;&gt;&gt; optimal_partition = [3, 2, 2, 1] &gt;&gt;&gt; optimal_partition_percent = zip(sorted(optimal_partition), sorted(enumerate(percent), key = itemgetter(1))) &gt;&gt;&gt; optimal_partition = [e for e, _ in sorted(optimal_partition_percent, key = lambda e: e[1][0])] &gt;&gt;&gt; optimal_partition [2, 2, 3, 1] </code></pre> <p>Can you suggest an easier way to solve this?</p> <p>By easier I mean, without the need to implement multiple sorting, and storing and later rearranging based on index.</p> <p>Couple of more examples:</p> <pre><code>percent = [0.25, 0.25, 0.4, 0.1] optimal_partition = [3, 2, 2, 1] result = [2, 2, 3, 1] percent = [0.2, 0.2, 0.4, 0.2] optimal_partition = [3, 2, 2, 1] result = [1, 2, 3, 2] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload