Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The hackery referred to by Laurence:</p> <p>You can do it in one list comprehension, it just ends up being AWFUL python. Unreadable python. Terrible python. I only present the following as a curiosity, not as an actual answer. Don't do this in code you actually want to use, only if you fancy having a play with the inner workings on python. </p> <p>So, 3 approaches: </p> <hr> <h2>Helping List 1</h2> <p>1: Using a helping list, answer ends up in the helping list. This appends values to the list being iterated over until you've reached the value you want to stop at.</p> <pre><code>A = [10] print [None if A[-1] == 1 else A.append(A[-1]/2) if (A[-1]%2==0) else A.append(3*A[-1]+1) for i in A] print A </code></pre> <p>result:</p> <pre><code>[None, None, None, None, None, None, None] [10, 5, 16, 8, 4, 2, 1] </code></pre> <hr> <h2>Helping List 2</h2> <p>2: Using a helping list, but with the result being the output of the list comprehension. This mostly relies on <code>list.append(...)</code> returning <code>None</code>, <code>not None</code> evaluating as <code>True</code> and <code>True</code> being considered <code>1</code> for the purposes of arithmetic. Sigh.</p> <pre><code>A=[10] print [A[0]*(not A.append(A[0])) if len(A) == 1 else 1 if A[-1] == 2 else (A[-1]/2)*(not A.append(A[-1]/2)) if (A[-1]%2==0) else (3*A[-1]+1)*(not A.append(3*A[-1]+1)) for i in A] </code></pre> <p>result:</p> <pre><code>[10, 5, 16, 8, 4, 2, 1] </code></pre> <hr> <h2>Referencing the List Comprehension from within</h2> <p>3: Not using a helping list, but referring back to the list comprehension as it's being built. This is a bit fragile, and probably wont work in all environments. If it doesn't work, try running the code on its own:</p> <pre><code>from itertools import chain, takewhile initialValue = 10 print [i if len(locals()['_[1]']) == 0 else (locals()['_[1]'][-1]/2) if (locals()['_[1]'][-1]%2==0) else (3*locals()['_[1]'][-1]+1) for i in takewhile(lambda x:x&gt;1, chain([initialValue],locals()['_[1]']))] </code></pre> <p>result:</p> <pre><code>[10, 5, 16, 8, 4, 2, 1] </code></pre> <hr> <p>So, now forget that you read this. This is dark, dark and dingy python. Evil python. And we all know python isn't evil. Python is lovely and nice. So you can't have read this, because this sort of thing can't exist. Good good. </p>
 

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