需要帮助在 Python 中使用数字制作希尔伯特曲线 [英] Need help making a Hilbert Curve using numbers in Python
问题描述
我想创建一个函数,在 python 中使用数字创建希尔伯特曲线.该函数的参数将是一个数字,它将告诉该函数应该重复多少次.要制作希尔伯特曲线,您以L"开头,然后变成+RF-LFL-FR+",然后R"变成-LF+RFR+FL-"我该怎么做?
I want to make a function that will create a Hilbert Curve in python using numbers. The parameters for the function would be a number and that will tell the function how many times it should repeat. To make a Hilbert Curve you start with 'L', then that turns into '+RF-LFL-FR+', and then 'R' turns into '-LF+RFR+FL-' How should I do this?
#Here is what I've made so far
def hilbert(num):
s = 'L'
for i in range(num-1):
s = s.replace('L','+RF-LFL-FR+')
b = 'R'
for i in range(num-1):
b = b.replace('R','-LR+RFR+FL-')
end = s + b
return end
当您输入 1 时它完全崩溃,我尝试使用我为 Koch 雪花编写的代码,但我不确定如何使用这两个变量.
It crashes completely when you enter 1, I tried to use to code I made for the Koch snowflake but I wasn't sure how to use the two variables.
#Here is the results for when I use the function
hilbert(1)
#It returns
a crash bruh
hilbert()
#It returns
'+RF-+RF-LFL-FR+F+RF-LFL-FR+-FR+-L-LR+RFR+FL-+-LR+RFR+FL-F-LR+RFR+FL-+FL-'
#Here is what I want it to return
hilbert(1)
'L'
hilbert(3)
'+-LF+RFR+FL-F-+RF-LFL-FR+F+RF-LFL-FR+-F-LF+RFR+FL-+'
我不太擅长范围循环,我该怎么做?
I'm not that good at the range loop, how should I do this?
推荐答案
在您提供的代码中,您使用 #1 作为输入进行测试.在这种情况下:
In the code you provided you are testing with # 1 as input. In this case:
for i in range(num-1):
未完成并且您的 for 循环从未初始化,因为您的 i 已经超过该范围.
is not fulfilled and your for-loop is never initialized since your i is already past that range.
您可以在下面看到一个示例代码,您可以在玩希尔伯特曲线时将其用作参考:
Below you can see a sample code that you can use as reference when playing with Hilbert Curve:
import turtle
turtle.speed(speed=10) # Fastest
hilbert_seq = "a"
for _ in range(5):
new_seq = ""
for char in hilbert_seq:
if char == "a":
new_seq += "-bF+aFa+Fb-"
elif char == "b":
new_seq += "+aF-bFb-Fa+"
else:
new_seq += char
hilbert_seq = new_seq
for char in hilbert_seq:
if char == "F":
turtle.forward(9)
elif char == "+":
turtle.right(90)
elif char == "-":
turtle.left(90)
上述示例代码的截图:
这篇关于需要帮助在 Python 中使用数字制作希尔伯特曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!