First solution in Clear category for Count Inversions by
Sept. 3, 2014
on Sept. 16, 2014, 9:43 p.m.
<p>I wouldn't call this clear but I like it as a one-liner.</p>
on Dec. 25, 2014, 5:43 a.m.
<p>good one-line solution</p>
on Jan. 10, 2015, 1:37 p.m.
<p>same logic as mine, elegant as a one liner, but not exactly clear.</p>
on Jan. 10, 2015, 4:46 p.m.
<p>That's a really smart way of solving this.</p>
<p>I really wish the clear category actually had clear problems upvoted to the top.
maybe we need a new category called "actually clear" or "clear to beginners"</p>
on Feb. 27, 2015, 6:54 a.m.
<p>I believe there should be a category called "concise" where these one-line solutions could be posted. I tend to be impressed by these solutions, but many of them may not be considered "clear".</p>
on Feb. 8, 2015, 4:55 p.m.
<p>Can you explain your solution?</p>
on Feb. 9, 2015, 1:04 a.m.
<p>It equals to:</p>
<pre class='brush: python'>def count_inversion(sequence):
count = 0
for i,n in enumerate(sequence): # for every number n in sequence
for m in sequence[i+1:]: # for every number m behind n
if m < n: # if there is a inversion
count = count + 1 # count 1 more
<p>The trick is that the value of (m < n) would be True or False and in Python they can be treated like 1 and 0. Thus you can sum a list of Trues and Falses. Obviously the result is the amount which True occurs. </p>
on April 28, 2015, 1:54 a.m.
<p>Nice one liner, but not Pythonic and not clear. </p>
on June 5, 2015, 10:15 a.m.
<p>Very well exploited!!</p>
on June 21, 2015, 1:57 a.m.
<p>OK. A smart solution using 'enumerate()'. But what about the comparison of the last value with a value from a 'null' list? I'm wondering how Python deals with that case and what Boolean value it returns. The above function works only if the result is 'False' for that comparison, and apparently, yes, it seems so.</p>
on June 21, 2015, 6:58 a.m.
<p>not clear, Speedy but not clear. </p>
on July 8, 2015, 12:43 p.m.
<p>Good solution, nice!</p>
on July 28, 2015, 12:10 p.m.
<p>nice one-liner but does not belong in the "clear" category imho</p>
on Sept. 5, 2015, 7:20 a.m.
on Oct. 29, 2015, 11:34 a.m.
<p>This is not clear solution, but creative.
Please, NEVER use such style in real projects</p>
on Nov. 5, 2015, 1:14 p.m.
<p>good for using `enmerate()` here.</p>
on Jan. 7, 2016, 7:18 a.m.
<p>I do not think this one can be categorized as clear</p>
on Jan. 10, 2016, 7:46 p.m.
<p>one line using lambda</p>
<pre class='brush: python'>count_inversion = lambda sequence: sum(sum(v > j for j in sequence[i+1:]) for i, v in enumerate(sequence))
on Jan. 16, 2016, 10:08 p.m.
<p>sum(sum(m<n for m in sequence[i:]) for i,n in enumerate(sequence)). </p>
on Jan. 20, 2016, 1:29 a.m.
<p>Yeah, they're same cuz m >= m always holds.</p>
Sept. 3, 2014