I havn't been able to find a solution to this problem on the internet (maybe im not looking hard enough) but i can't figure out how to make an input only take numbers. Im trying to get the input to go through some equations and the program brakes everytime i put a letter in the input. I was wondering if there was a way to detect if the input was a letter or number. I'll show my program.
Radius=input("What is the radius of the circle/sphere?")
Areacircle=(int(Radius)**2)*3.14159265359
Perimetercircle=2*3.14159265359*int(Radius)
Permsphere=4*3.14159265359*(int(Radius)**2)
Areasphere=(4/3)*3.14159265359*(int(Radius)**3)
print("The radius' length was:",Radius)
print("The surface area of each circle is:",Areacircle)
print("The perimeter of the circle is:",Perimetercircle)
print("The volume of the sphere would be:",Areasphere)
print("The perimeter of the Sphere would be:",Permsphere)
As suggested in the comments, you can handle a ValueError when the conversion to int fails (and save doing this same conversion throughout the rest of your code).
Radius = None
while not Radius:
unchecked_radius = input("What is the radius of the circle/sphere? ")
try:
Radius = int(unchecked_radius)
except ValueError:
print('"{}" is not an integer. Redo.'.format(unchecked_radius))
I recommend reading the Python Tutorial section on Handling Exceptions, which has a very similar example.
Related
I'm looking for an algorithm (or pseudo code) that can calculate the maximum number of (smaller) circles with diameter "s" that can be squeezed into the circumference of another (larger) circle with radius "r" ...
Image: http://teasy.space/images/terracolony-squeezingcircles2.jpg
You can alternate between radius/diameter etc if you wish -- as these are the only 2 parameters (other than the center (large circle) coordinate) that i have, i.e. that are known ...
The outer circles may not overlap but can fit "snug" together ...
After various upgrades to my routine through the years, I'm currently using an algorithm that is not perfect (and it needs to be accurate or the galaxy breaks down lol)
which does a broad interpolation between small outside circle diameter and large inside circle circumference, to somewhat accurately plot the circle count in a polygon style fitting pattern, which causes problems (i.e. overlaps) when using larger outside circles ...
; try to fit a random number of circles
num_Circles = Rand( min,max )
; check if the number of circles exceed the maximum that can fit
If num_Circles * SmallCircle_Diameter > LargeCircle_Circumference
; adjust the amount accordingly
num_Circles = LargeCircle_Circumference / SmallCircle_Diameter
End If
Another assumption is that the size of the smaller outer circles never exceeds that of the larger inner circle ...
something less to worry about ;)
I'm using this algorithm for one of my projects called Terra Colony, based on Gravity Well, a 2D space/gravity realtime colonization simulation game with moons, planets, stars, black/white holes, etc
Image: http://teasy.space/images/terracolony-squeezingcircles1.jpg
This is an issue that has plagued this project for over a decade!
Hopefully you can point me in the right direction :D
I have previously done many experiments and wrote different programs to find a solution, and have traveled the internet looking for formulas and solutions which in the end are very close, but not close enough! :P
Thank you! <3
Teasy
P.S. I tried to add the tag "circumference" but it apparently requires "1500 reputation" (points i guess, maybe to prevent spam)
There is formula that establishes relation between radius of big circle R, radius of small circle r and number of (touching) small circles N
R = r / Sin(Pi/N)
So maximum number of small circles might be found as
Sin(Pi/N) = r / R
Pi / N = arcsin(r / R)
and finally
N = Pi / arcsin(r / R)
Example:
R=5
r=2.5
so
N = Pi / arcsin(1/2) =
Pi / (Pi/6) =
6
Given the diam. of the small circle 'd' and the number of them 'c'
then the dia. of the large circle 'D' is
D=d/sin(180/c)
I am working on CT scan images and I want to extract a small patch from cancer location of scans for example (16,40,40)(z,y,x), sometimes the location are on the corners and cannot get the size that decided before, for solving that problem tried to do padding in all side, here is my code:
M,N,P=(16,40,40)
temp_img = np.ndarray([16,40,40],dtype=np.float32)
center = np.array([node_z, node_y, node_x]) # nodule center
v_center = np.rint((center-origin)/spacing) # nodule center in voxel space (still x,y,z ordering)
temp_imgtemp_img[:,:,:] = img_array[int(v_center[0]-(M/2)):int(v_center[0]+(M/2)),\
int(v_center[1]-(N/2)):int(v_center[1]+(N/2)),\
int(v_center[2]-(P/2)):int(v_center[2]+(P/2))]
m,n,p=temp_img.shape
a1,a2,b1,b2,c1,c2=0,0,0,0,0,0
if (m,n,p) != (M,N,P):
if m != M:
a=M-m
a1=a/2
a2=a-a1
if n != N:
b=N-n
b1=b/2
b2=b-b1
if p != P:
c=P-p
c1=c/2
c2=c-c1
transform=((a1,a2),(b1,b2),(c1,c2))
temp_img = np.pad(temp_img,transform,'linear_ramp')
plt.imshow(temp_img[5], cmap='gray')
plt.title('image')
plt.grid(which='major', linewidth='0.8', color='red')
plt.show()
but I get an error:
TypeError: `pad_width` must be of integral type.
by changing a1=a/2 to a1=a//2 as suggested in one of the answers below the above problem is solved but I get the new error:
could not broadcast input array from shape (20,50,50) into shape (25,50,50)
which means that my real problem is not solved, cuz when tried this solution the value is rounded and the shape gets smaller or begger than specified shape.
The error stems from here:
a1=a/2
If a is odd, a1 will be a floating point number. So you should do a truncating divide like a//2 or round and cast back to int like int(round(a/2)).
Python developers
I am working on spectroscopy in a university. My experimental 1-D data sometimes shows "cosmic ray", 3-pixel ultra-high intensity, which is not what I want to analyze. So I want to remove this kind of weird peaks.
Does anybody know how to fix this issue in Python 3?
Thanks in advance!!
A simple solution could be to use the algorithm proposed by Whitaker and Hayes, in which they use modified z scores on the derivative of the spectrum. This medium post explains how it works and its implementation in python https://towardsdatascience.com/removing-spikes-from-raman-spectra-8a9fdda0ac22 .
The idea is to calculate the modified z scores of the spectra derivatives and apply a threshold to detect the cosmic spikes. Afterwards, a fixer is applied to remove the spike points and replace it by the mean values of the surrounding pixels.
# definition of a function to calculate the modified z score.
def modified_z_score(intensity):
median_int = np.median(intensity)
mad_int = np.median([np.abs(intensity - median_int)])
modified_z_scores = 0.6745 * (intensity - median_int) / mad_int
return modified_z_scores
# Once the spike detection works, the spectrum can be fixed by calculating the average of the previous and the next point to the spike. y is the intensity values of a spectrum, m is the window which we will use to calculate the mean.
def fixer(y,m):
threshold = 7 # binarization threshold.
spikes = abs(np.array(modified_z_score(np.diff(y)))) > threshold
y_out = y.copy() # So we don't overwrite y
for i in np.arange(len(spikes)):
if spikes[i] != 0: # If we have an spike in position i
w = np.arange(i-m,i+1+m) # we select 2 m + 1 points around our spike
w2 = w[spikes[w] == 0] # From such interval, we choose the ones which are not spikes
y_out[i] = np.mean(y[w2]) # and we average the value
return y_out
The answer depends a on what your data looks like: If you have access to two-dimensional CCD readouts that the one-dimensional spectra were created from, then you can use the lacosmic module to get rid of the cosmic rays there. If you have only one-dimensional spectra, but multiple spectra from the same source, then a quick ad-hoc fix is to make a rough normalisation of the spectra and remove those pixels that are several times brighter than the corresponding pixels in the other spectra. If you have only one one-dimensional spectrum from each source, then a less reliable option is to remove all pixels that are much brighter than their neighbours. (Depending on the shape of your cosmics, you may even want to remove the nearest 5 pixels or something, to catch the wings of the cosmic ray peak as well).
I'm having a problem that I need to make the words I took from an external file "NOT" overlap each other. I have over 50 words that have random text sizes and places when you run it but they overlap.
How can I make them "NOT" overlap each other? the result would probably look like a word cloud.
if you think my codes would help here they are
String [] words;
int index = 0;
void setup ()
{
size (500,500);
background (255);
String [] lines = loadStrings ("alice_just_text.txt");
String entireplay = join(lines, " "); //splits it by line
words = splitTokens (entireplay, ",.?!:-;:()03 "); //splits it by word
for (int i = 0; i < 50; i++) {
float x = random(width);
float y = random(height);
int index = int(random(words.length));
textSize (random(60)); //random font size
fill (0);
textAlign (CENTER);
text (words[index], x, y, width/2, height/2);
println(words[index]);
index++ ;
}
}
Stack Overflow isn't really designed for general "how do I do this" type questions. You'll have much better luck if you post a more specific "I tried X, expected Y, but got Z instead" type question. But I'll try to help in a general sense:
You need to break your problem down into smaller pieces and then take on those pieces one at a time.
For example, you can isolate your problem to making sure rectangles don't overlap, which you can break down even further. There are a number of ways to do that:
You could use a grid to lay out your rectangles. Figure out how many squares a line of text takes up, then find a place in your grid where that word will fit. You could use something like a 2D array of boolean values, for example.
Or you could generate a random location, and then check whether there's already a rectangle there. If so, pick a new random location until you find a clear spot.
In any case, you'll probably need to use collision detection (either point-rectangle or rectangle-rectangle) to determine whether your rectangles are overlapping.
Start small. Create a small example program that just shows two rectangles on the screen. Hardcode their positions at first, but make it so they turn red if they're colliding. Work your way up from there. Make it so you can add rectangles using the mouse, but only let the user add them if there is no overlap. Then add the random location choosing. If you get stuck on a specific step, then post a MCVE and we'll go from there. Good luck.
This is a very basic question as I am new to computer programming but I am having problems. The question is asking me to write in Python 3 an equation for area of a rectangle that allows the user to input the width and length in square feet and output the answer in square feet. This is what I've tried:
width = int(input("What is the width of the rectangle?")
10 ft^2
length = int(input("What is the length of the rectangle?")
5 ft^2
area = str(length*width("feet squared.")
but I get errors when even trying to input an integer with "feet squared" attached to it. Can anybody help me?
You must change the area assigment part to,
area = str(length*width) + " feet squared."
That is you must use the string concatenation operator + here.
or
area = "{0} feet squared.".format(length*width)
Example answer using numbers following rules stated in question:
width = input("What is the width of the rectangle?"
# What is the width of the rectangle? 10
length = input("What is the length of the rectangle?")
# What is the width of the rectangle? 5
area = "{0} feet squared.".format(length*width)
print(area)
# 50 feet squared.