Note that there are some explanatory texts on larger screens.

plurals
  1. POIterating Lists in Python, Ruby, Haskell (or whatever)
    primarykey
    data
    text
    <p><strong>Update: I realize that I put the question very badly. Here's a second run.</strong></p> <p>Consider the following function:</p> <pre><code>myList = [] optimumList = [] def findOptimumListItems(): n = 5 for i in range (n + 1): for j in range (n + 1 - i): myList.append((i, j, n-i-j)) for i in myList: win = 0.0 draw = 0.0 for j in myList: score = 0 if (i[0] &gt; j[0]): score += 1 if (i[0] == j[0]): score += 0.5 if (i[1] &gt; j[1]): score += 1 if (i[1] == j[1]): score += 0.5 if (i[2] &gt; j[2]): score += 1 if (i[2] == j[2]): score += 0.5 if (score == 2): win += 1 if (score == 1.5): draw += 1 if (win/(len(myList)-win-draw) &gt; 1.0): optimumList.append(i) return optimumList </code></pre> <p>First I make a list. For n = 5 the generated list is:</p> <pre><code>[(0, 0, 5), (0, 1, 4), (0, 2, 3), (0, 3, 2), (0, 4, 1), (0, 5, 0), (1, 0, 4), (1, 1, 3), (1, 2, 2), (1, 3, 1), (1, 4, 0), (2, 0, 3), (2, 1, 2), (2, 2, 1), (2, 3, 0), (3, 0, 2), (3, 1, 1), (3, 2, 0), (4, 0, 1), (4, 1, 0), (5, 0, 0)] </code></pre> <p>Then, the function takes each element of the list and compares it with the list itself. This is how you do it: Say I'm comparing [0, 0, 5] against [3, 1, 1]. 0 loses to 3 (so no points), 0 loses to 1, so no points, 5 wins against 1 (1 point for that). A draw gets 0.5 points, a win gets 1 point. For any item, if wins are more than loses then that item is considered optimum and is added to the optimum list.</p> <p>For n = 5, the optimum list is:</p> <pre><code>[(0, 2, 3), (0, 3, 2), (1, 1, 3), (1, 2, 2), (1, 3, 1), (2, 0, 3), (2, 1, 2), (2, 2, 1), (2, 3, 0), (3, 0, 2), (3, 1, 1), (3, 2, 0)] </code></pre> <p>My question is: How can I write the above function in a <strong>concise</strong> way? I'm especially interested in functional algorithms. Python, Ruby, Java, Haskell answers will be appreciated. (Having said that, if you have a neat solution in any language; that's okay.)</p> <p>Sorry for repeating the same question. I agree that the original question was messy and hard to understand. I hope it's clear now.</p> <p><strong>Update (upon rampion's comment):</strong> Is there an efficient algorithm for this (or this type) problem?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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