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-+'
Related
I'm trying to make a program to calculate the surface area of a shack with a pitched roof. I've only been in this class for 2 weeks and I'm a bit overwhelmed. The program should ask the user via console for the values and then calculate the values using the definition.
I'm not asking for the entire code at all. But I don't understand how I can calculate inputs using a definition and then print them. this is my code so far:
import math
def floorspace(a,b):
G = 0
G = a*b
return (G)
#main program
a = int(input("enter the length of the floor!"))
b = int(input("Enter the width of the floor!"))
print(floorspace, G)
You don't need to import math as basic multiplication is already included. You also don't need to initialize a variable before you assign it so I removed the
G = 0
G = a*b
lines and replaced it with a simple
return a*b
You don't need brackets around a return statement, just a print statement.
The final two issues are that you're printing incorrectly and you used the wrong function parameters. You would need to pass in the same number of parameters that are in the function declaration (so in this case, 2). Pass in a and b from the user inputs into your floorspace() function and then call print(). The code should work now!
def floorspace(a,b):
return a*b
#main program
a = int(input("enter the length of the floor!"))
b = int(input("Enter the width of the floor!"))
print(floorspace(a,b))
in your code print(floorspace,G) G is not defined you must write your it like this print(floorspace(a,b))
I'm attempting to create a game similar to battleship, and I'm having trouble figuring out how I would initialize the board by having each cell begin with an 'O' and displaying it to the user. A requirement for the function player_board() is that it's supposed to take in a grid representing the player's game board as an argument and output it to the user's screen. This is a portion of my code that I'm struggling with. I'm also not sure why it keeps printing out an extra 'O' at the end. Any help or feedback would be appreciated!
import random
sizeof_grid = 9
chance = 10
def mines():
grid = [{("M" if random.randint(0, chance) == 0 else " ") for i in
range(sizeof_grid)} for i in range(sizeof_grid)]
return grid
def initialize_board():
start_board=[["O" for i in range(sizeof_grid)] for i in range(sizeof_grid)]
return start_board
def players_board():
for r in initialize_board():
for c in r:
print (c, end="")
print()
return c
print(players_board())
You get the extra "O: because of the last line of code. You call the function with print(players_board) and in the function itself you return c (which has the value of one "O"). This means you print out the return value of the function which is "O".
You can execute the function with players_board() and remove the print().
Also you can remove the return c at the bottom of the function.
I'm new to programming and only started writing my first lines of code last week.
I'm writing a script in a program called dynamo, this is to be used in my project. After some research, it appears like I need to use python.
What I need to script to do is look at a bunch of lines ( In a program called Revit), pick up the geometry of this line and then detect if any other line has a start point or end point that is in contact with that geometry. I then want to Split that line at that point, this can be done byCurve.SplitByPoints but I need some kind of way to compare ALL lines to ALL start/end points then the output be in a way that the output can be used to split the curve by the point. I can have the line and the point in which to cut in.
I tried to explain that the best I could...
code :
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
dataEnteringNode = IN
Line = IN[0] #Line
LPS = IN[1] # Line Point Start
LPE = IN[2] # Line Point End
LPC = IN[3] # Line Point Combined // Maybe not needed
T = 100 # Tolerance of Intersection
INT1 = [] # Blank Variable for First Loop Results
INT2 = [] # Blank Variable for First Loop Results
result1 = [] # Blank Variable for Second Loop Results
result2 =[] # Blank Variable for Second Loop Results
for i in range (0,len(LPS)):
distance = Curve.DistanceTo(LPS[i],Line[i])
INT1.append(distance)
for i in range (0,len(LPE)):
distance = Curve.DistanceTo(LPE[i],Line[i])
INT2.append(distance)
for i in range (0,len(INT1)):
if INT1 > T:
result1.append('T1')
else:
result1.append('F1')
for i in range (0,len(INT2)):
if INT2 > T:
result2.append('T2')
else:
result2.append('F2')
Assign your output to the OUT variable.
OUT = result1, result2
EDIT:
Sorry, I knew explaining this would be tricky for me.
I'll attempt to simplify it.
I want something like:
if curve intersect with StartPoint or EndPoint
Curve.split points(Curve,Intersecting_Point)
So im hoping something similar will have it so, when a start or end point intersects a curve, the curve will be split into 2 curves at that point.
So I want to above for to work on a range of lines. I drew a diagram and attempted to upload, but for some reason, it now says I need 10 rep to post an image. meaning I cant upload a new diagram and had to remove the ones I had in?
Thanks for the help! I'm sorry for my explaination skills
I've been write this practice program for while now, the whole purpose of the code is to get user input and generate passwords, everything almost works, but the replace statements are driving me nuts. Maybe one of you smart programmers can help me, because I'm kinda new to this whole field of programming. The issue is that replace statement only seems to work with the first char in Strng, but not the others one. The other funcs blower the last run first and then the middle one runs.
def Manip(Strng):
#Strng = 'jayjay'
print (Strng.replace('j','h',1))
#Displays: 'hayjay'
print (Strng.replace('j','h',4))
#Displays: 'hayhay'
return
def Add_nums(Strng):
Size=len(str(Strng))
Total_per = str(Strng).count('%')
# Get The % Spots Position, So they only get replaced with numbers during permutation
currnt_Pos = 0
per = [] # % position per for percent
rGen = ''
for i in str(Strng):
if i == str('%'):
per.append(currnt_Pos)
currnt_Pos+=1
for num,pos in zip(str(self.ints),per):
rGen = Strng.replace(str(Strng[pos]),str(num),4);
return rGen
for pos in AlphaB: # DataBase Of The Positions Of Alphabets
for letter in self.alphas: #letters in The User Inputs
GenPass=(self.forms.replace(self.forms[pos],letter,int(pos)))
# Not Fully Formatted yet; you got something like Cat%%%, so you can use another function to change % to nums
# And use the permutations function to generate other passwrds and then
# continue to the rest of this for loop which will generate something like cat222 or cat333
Add_nums(GenPass) # The Function That will add numbers to the Cat%%%
print (rGen);exit()
I am making a program for my own purposes (a naming program) that completely generates a random name. The problem is I cannot assign a number to a letter, so as a being 1 and z being 26, or a being 0 and z being 25. It gives me a SyntaxError. I need to assign this because the random integer (1,26) triggers a letter (if the random integer is 1, select A) and prints the name.
EDIT:
I have implemented your advice, and it works, I am grateful for this, but I wish to have my program create readable names, or more procedural. Here is an example of a name after I tweaked my program: ddjau. Now that doesn't look like a name, so I want it my program to work as if it were creating REAL names, like Samuel or other common names. Thanks!
EDIT (2):
Thanks, Adam, but I need a sort of 'seed' for the user to enter for the start of the name is. (Seed = A, Name = Adam. Seed = G, Name = George.) Should I do this by searching the file line by line, at the very beginning? If so, how do I do this?
Short Answer
Look into Python dictionaries to allow the 1 = 'a' type assignments. Below I have working example that would generate a random name based on gender and a 'litter'.
Disclaimer
I do not fully understand (via the code) what you're trying to accomplish with char/ord and a random letter. Also note having absolutely no idea of your design goals or requirements, I have made the example more complex than it may need to be for instructional purposes.
Additional Resources
* Python Docs for dictionary
* Using Python dictionary relationship to search both ways
In response to the last edit
If you are looking to build random 'real' names, I think your best bet will be to use a large list of names and just pick a random one. If I were you I'd look into something linking to the census results: males and females. Note that male_names.txt and female_names.txt are a copy of the list found at the census website. As a disclaimer, I'm sure there is a more efficient way to load / read the file. Just use this example as a proof on concept.
Update
Here's a quick and dirty way to seed the random values. Again I am not sure that this is the most pythonic way or most efficient way, but it works.
Example
import random
import time
def get_random_name(gender, seed):
if(gender == 'male'):
file = 'male_names.txt'
elif(gender == 'female'):
file = 'female_names.txt'
fid = open(file,'r')
names = []
total_names = 0
for line in fid:
if(line.lower().startswith(seed)):
names.append(line)
total_names = total_names + 1
random_index = random.randint(0,total_names)
return names[random_index]
if (__name__ == "__main__"):
print 'Welcome to Name Database 2.2\n'
print '1. Boy'
print '2. Girl'
bog = raw_input('\nGender: ')
print 'What should the name start with?'
print 'A, Ab, Abc, B, Ba, Br, etc...'
print ''
l = raw_input('Leter(s): ').lower()
new_name = ''
if bog == '1': # Boy
print get_random_name('male',l)
elif bog == '2':
print get_random_name('female',l)
Output
Welcome to Name Database 2.2
1. Boy
2. Girl
Gender: 2
What should the name start with?
A, Ab, Abc, B, Ba, Br, etc...
Leter(s): br
BRITTA
chr (see here) and ord (see here) are the two functions you're looking for (though you already seem to know about the latter). Follow those links for a more detailed explanation.
The first gives you a one-character string based on the integer, the second does the reverse operaion (technically, it handles Unicode as well, which chr doesn't, though you have unichr for that if you need it).
You can base your code on the following:
ch = "E"
print ord (ch) - ord ("A") + 1 # should give 5 for the fifth letter
val = 7
print chr (val + ord ("A") - 1) # should give G, the seventh letter
I'm not entirely sure what you're trying to do, but you can convert a number into a letter with the chr() function. chr() takes an ASCII code, so if you want to use the range [0, 25] instead you can adapt it like so:
chr(25 + ord('a')) # 'z'