擅长:python、mysql、java
<p>Python没有内置这种控制结构,但是您可以将其归纳为这样的函数:</p>
<pre><code>def unfold(evolve, initial, until):
state = initial
yield state
while not until(state):
state = evolve(state)
yield state
</code></pre>
<p>在此之后,您的表达式可以写成:</p>
<pre><code>def is_even(n): return not n % 2
unfold(lambda x: x/2 if is_even(x) else 3*x + 1,
initial=input, until=lambda x: x == 1)
</code></pre>
<p>但是python的方法是使用一个生成器函数:</p>
<pre><code>def produce(x):
yield x
while x != 1:
x = x / 2 if is_even(x) else 3*x + 1
yield x
</code></pre>