首先,如果这是问题所在:一个大的 Levy 曲线(递归情况)是通过将两个较小的曲线“穿过房间”布置成彼此相对的,另外两个“在地板上”朝上,介于两者之间。一条小的 Levy 曲线(基本情况)只是一条直线。事实上,基本情况是:
def lev(n):
if n == 0:
return 'F'
else:
# Recursive case here
但是对于递归的情况,你只需调用 lev(n-1)。你是对的,你需要这样做,但你需要做四次,并在两者之间轮换。这将创建所需的“两条彼此相对的较小曲线,中间有两条曲线”。
仔细检查曲线(这里:https ://en.wikipedia.org/wiki/File:Levy_C_construction.png ),我们看到我们需要画一条曲线,然后右转,然后画另一条,然后完全转身,然后画第三条曲线,最后右转,画出最后一条曲线。
这可以相当简单地完成:
dev lev(n):
if n == 0:
# Base case
return 'F'
else:
# Recursive case
# Calculate the smaller curve
smaller = lev(n-1)
# Add in the turning in between the smaller curves
final = smaller # First curve
if n%2 == 0: # Even depths require right turns
final += 'RR' # Rotate 90 degrees
final += smaller # Second curve
final += 'RRRR' # Rotate 180 degrees
final += smaller # Third curve
final += 'RR' # Rotate 90 degrees
final += smaller # Final curve
else: # Odd depths require left turns
final += 'LL' # Rotate 90 degrees
final += smaller # Second curve
# (No full rotation in odd depths)
final += smaller # Third curve
final += 'LL' # Rotate 90 degrees
final += smaller # Final curve
return final # Done!