问题
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
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):
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)
Screenshot from the above sample code:
来源:https://stackoverflow.com/questions/58713316/need-help-making-a-hilbert-curve-using-numbers-in-python