Printing a hollow circle using asterisks (so no turtle) - python-3.x

For a school assignment I need to print a smiley using a hollow circle.
def circle(i):
i += 1
from math import sqrt
result = ""
midden = i / 2.0
for a in range(i):
for b in range(i):
c = sqrt((midden - a)**2 + (midden - b)**2)
if midden > c:
result += "#"
else:
result += " "
result += "\n"
print(result)
circle(11)
The code above is what I have used to print a filled circle but i cannot for the life of me figure out how to make the circle hollow

Here is code that will first create a matrix with spaces, and walks along 1/8th of the circle, placing '#' characters. The 7 mirroring positions can be set at the same time, filling the complete circle. Finally the matrix is converted to a string which is returned.
from math import sqrt
def circle(radius):
pixels = [[' ' for x in range(2*radius+1)] for y in range(2*radius+1)]
y = radius
x = 0
max = (radius + 0.5)**2
while x <= y:
pixels[radius+y][radius+x] = '#'
pixels[radius+y][radius-x] = '#'
pixels[radius-y][radius+x] = '#'
pixels[radius-y][radius-x] = '#'
pixels[radius+x][radius+y] = '#'
pixels[radius+x][radius-y] = '#'
pixels[radius-x][radius+y] = '#'
pixels[radius-x][radius-y] = '#'
x += 1
if x*x + y*y >= max:
y -= 1
return '\n'.join([''.join([v for v in row]) for row in pixels])
print(circle(11))

Related

Undesired effect with dictionaries in python

Currently working with sensor data processing in python.
Idea and concept:
Sensor data is in the form of range (points x, y, z). Identify the cube to which each point belongs and find the mean for each and every cell and store the value in a dictionary in which the key represents the dimensions of the cell and the value corresponds to the mean of the points in that particular cell.
Issue / abnormality:
For every cell the idea works fine untill the second point gets identified for each cell. From the second point onwards association fails, meaning the stored value in the dictionary is erratic and not the calculated value.
The code is as follows:
covMats = {}
meanMats = {}
countMats = {}
pointsMat = {}
mean1 = np.array([[0.0, 0.0, 0.0]])
for point in radarData:
xmin, ymin, zmin, xmax, ymax, zmax, timetaken = returnExtreme(point)
cellID = str(xmin) + ',' + str(ymin) + ',' + str(zmin) + ',' + str(xmax) + ',' + str(ymax) + ',' + str(zmax) ## Gives the extreme ends of a cell (xmin, ymin, zmin, xmax, ymax, zmax) , a unique key for every cube
mean1[0, 0] = point[0]
mean1[0, 1] = point[1]
mean1[0, 2] = point[2]
tempPoint = np.array([point])
if(cellID in meanMats): ## If the cell ID already exist
currentMean = meanMats[cellID]
currentMean += tempPoint
tempArray = pointsMat[cellID]
count = 0
for temp in tempArray: ## To remove duplicate of points
#print("The value in temp is ", temp[0])
if temp[0] == point[0]:
if temp[1] == point[1]:
if temp[2] == point[2]:
count += 1
#print("The length of the temp array is ", len(tempArray))
if count == 0:
tempArray.append([point[0], point[1], point[2]])
pointsMat[cellID] = tempArray
countMats[cellID] += 1
meanMats[cellID] = currentMean
count = 0
else: ## If a new point for a particular cell id
tempList = []
meanMats[cellID] = np.copy(mean1) ## Store the first point in the cell or cube
countMats[cellID] = 1
tempList.append([point[0], point[1], point[2]])
pointsMat[cellID] = tempList ## Update the parameters for that particular cube or cell.
Note:
The work cell and cube are invariant and are used interchangeably as they are the same. In my case a cell is cube in 3D visualisation.

Python(AI Constraint satisfaction problem) Fitting square and/or rectangular (2d) tiles onto a rectangular ground

I have to arrange and/or fit 2d tiles into a 2d square or rectangular plane with AI algorithm using python program. Each tile has a length and width. For example if a plane is 4x3 and set of tiles is
S={(2,3),(1,2),(2,2)}
these tiles can be rotated 90 degrees in order to fit the matrix.
input
first line contains length and width of the plane
second line number of tiles
and then the length,width of the subsequent tiles
but the inputs should be tab seperated
for eg
4 3
3
2 3
1 2
2 2
output
for eg
1 1 2 2
1 1 3 3
1 1 3 3
I have trouble solving this as i have to use only standard libraries in python no NumPy and no CSP library
~Edit 2`
my code so far I cant figure out how to add algorithm without csp library or to generate grid
from sys import stdin
a = stdin.readline()
x = a.split()
rectangular_plane = [[0] * int(x[0]) for i in range(int(x[1]))]
num_of_rectangles = stdin.readline()
r_widths = []
r_lengths= []
for l in range(int(num_of_rectangles)):
b = stdin.readline()
y = b.split()
r_lengths.insert(l,y[0])
r_widths.insert(l,y[1])
I've solved task with backtracking approach and without any non-standard modules.
Try it online!
import sys
nums = list(map(int, sys.stdin.read().split()))
pw, ph = nums[0:2]
ts = list(zip(nums[3::2], nums[4::2]))
assert len(ts) == nums[2]
if sum([e[0] * e[1] for e in ts]) != pw * ph:
print('Not possible!')
else:
def Solve(*, it = 0, p = None):
if p is None:
p = [[0] * pw for i in range(ph)]
if it >= len(ts):
for e0 in p:
for e1 in e0:
print(e1, end = ' ')
print()
return True
for tw, th in [(ts[it][0], ts[it][1]), (ts[it][1], ts[it][0])]:
zw = [0] * tw
ow = [it + 1] * tw
for i in range(ph - th + 1):
for j in range(pw - tw + 1):
if all(p[k][j : j + tw] == zw for k in range(i, i + th)):
for k in range(i, i + th):
p[k][j : j + tw] = ow
if Solve(it = it + 1, p = p):
return True
for k in range(i, i + th):
p[k][j : j + tw] = zw
return False
if not Solve():
print('Not possible!')
Example input:
4 3
3
2 3
1 2
2 2
Output:
1 1 2 2
1 1 3 3
1 1 3 3

How to make algorithm of counting big negative numbers faster?

I was trying to do a program which can take square matrix of any size and find two any square submatrixes(they shouldn't overlap), whose qualities are the closest. So every elementary square in matrix has a quality(any number). The problem is algorithm is too slow with processing matrixes 100*100 containing big negative numbers(-10^8).
from collections import defaultdict
from math import fsum
from itertools import islice, count
def matrix():
matritsa = list()
koord = list()
ssum = 0
diff = defaultdict(list)
size = int(input()) #size of the matrix
for line in range(size):
matritsa += list(map(int,input().split())) #filling the matrix
Q1,Q2 = map(int,input().split()) #quality range
for i in range(len(matritsa)):
element = matritsa[i]
if Q1 <= element and element <= Q2: #checking if an element is in range
koord.append([element, i//size, i%size, 1]) #coordinates of 1*1 elements
for razmer in range(2,size): #taking squares of 2+ size
#print("Razmer: ",razmer)
for a in range(len(matritsa)):
(x,y) = a//size,a%size #coordinates of the left top square
if y + razmer > size:
continue
ssum = 0
for b in range(x,x+razmer):
ssum += sum(matritsa[b*size+y:b*size+(y+razmer)])
if Q1 <= ssum and ssum <= Q2: #checking if it is in quality range
koord.append([ssum,x,y,razmer])
#print(koord)
#print("Coordinate: {0},{1}; ssum: {2}".format(x,y,ssum))
if x + razmer == size and y + razmer == size:
#print("Final: {0},{1}".format(x,y))
break
g = 0
temp = len(koord)
while g != temp:
(value1,x1,y1,a) = koord[g]
for i in range(g,temp - 1):
(value2,x2,y2,b) = koord[i+1]
if y1 >= y2 + b or y2 >= y1 + a:
diff[abs(value1 - value2)].append([value1,value2])
if x1 >= x2 + b or x2 >= x1 + a:
diff[abs(value1 - value2)].append([value1,value2])
g += 1
minimum = min(diff.keys())
if minimum == 0:
print(*max(diff[minimum]))
elif len(diff[minimum]) > 1:
maximum = sum(diff[minimum][0])
result = diff[minimum][0]
for pair in diff[minimum]:
if sum(pair) > maximum:
maximum = sum(pair)
result = pair
The problem is in this part
g = 0
temp = len(koord)
print(temp)
while g != temp:
(value1,x1,y1,a) = koord[g]
for i in range(g,temp - 1):
(value2,x2,y2,b) = koord[i+1]
if y1 >= y2 + b or y2 >= y1 + a:
diff[abs(value1 - value2)].append([value1,value2])
if x1 >= x2 + b or x2 >= x1 + a:
diff[abs(value1 - value2)].append([value1,value2])
g += 1

How to calculate points y position on arc? When i have radius, arcs starting and ending points

I'm trying to write a program on CNC. Basically I have circular arc starting x, y , radius and finishing x, y also I know the direction of the arc clockwise or cc. So I need to find out the value of y on the arc at the specific x position. What is the best way to do that?
I found similar problem on this website here. But i not sure how to get angle a.
At first you have to find circle equation. Let's start point Pst = (xs,ys), end point Pend = (xend,yend)
For simplicity shift all coordinates by (-xs, -ys), so start point becomes coordinate origin.
New Pend' = (xend-xs,yend-ys) = (xe, ye), new 'random point' coordinate is xr' = xrandom - xs, unknown circle center is (xc, yc)
xc^2 + yc^2 = R^2 {1}
(xc - xe)^2 + (yc-ye)^2 = R^2 {2} //open the brackets
xc^2 - 2*xc*xe + xe^2 + yc^2 - 2*yc*ye + ye^2 = R^2 {2'}
subtract {2'} from {1}
2*xc*xe - xe^2 + 2*yc*ye - ye^2 = 0 {3}
yc = (xe^2 + ye^2 - 2*xc*xe) / (2*ye) {4}
substitute {4} in {1}
xc^2 + (xe^2 + ye^2 - 2*xc*xe)^2 / (4*ye^2) = R^2 {5}
solve quadratic equation {5} for xc, choose right root (corresponding to arc direction), find yc
having center coordinates (xc, yc), write
yr' = yc +- Sqrt(R^2 -(xc-xr')^2) //choose right sign if root exists
and finally exclude coordinate shift
yrandom = yr' + ys
equation of a circle is x^2 + y^2 = r^2
in your case, we know x_random and R
substituting in knows we get,
x_random ^ 2 + y_random ^ 2 = R ^ 2
and solving for y_random get get
y_random = sqrt( R ^ 2 - x_random ^ 2 )
Now we have y_random
Edit: this will only work if your arc is a circular arc and not an elliptical arc
to adapt this answer to an ellipse, you'll need to use this equation, instead of the equation of a circle
( x ^ 2 / a ^ 2 ) + ( y ^ 2 / b ^ 2 ) = 1, where a is the radius along the x axis and b is the radius along y axis
Simple script to read data from a file called data.txt and compute a series of y_random values and write them to a file called out.txt
import math
def fromFile():
fileIn = open('data.txt', 'r')
output = ''
for line in fileIn:
data = line.split()
# line of data should be in the following format
# x h k r
x = float(data[0])
h = float(data[1])
k = float(data[2])
r = float(data[3])
y = math.sqrt(r**2 - (x-h)**2)+k
if ('\n' in line):
output += line[:-1] + ' | y = ' + str(y) + '\n'
else:
output += line + ' | y = ' + str(y)
print(output)
fileOut = open('out.txt', 'w')
fileOut.write(output)
fileIn.close()
fileOut.close()
if __name__ == '__main__':
fromFile()
data.txt should be formatted as such
x0 h0 k0 r0
x1 h1 k1 r1
x2 h2 k2 r2
... for as many lines as required

is inputted point within the rectangle centered on the (0,0) axis

Trying to write a simple python program to determine if two points (x, y) input by a user fall within a rectangle centered on the (0,0) axis with a width of 10 and height of 5.
Here is where I am.
x = eval(input("Enter the x point : "))
y = eval(input("Enter the y point : "))
if x <= 10.0 / 2:
if y <= 5.0 / 2:
print("Point (" + str(x) + ", " + str(y) + ") is in the rectangle")
else:
print("Point (" + str(x) + ", " + str(y) + ") is not in the rectangle")
This wont work on the negative side. There is a math function I am needing, just can't figure out which one.
I have added a distance = math.sqrt (( x * x ) + ( y * y )) and changed the ifs to distance instead of x and y. I am just so confused.
WIDTH = 10
HEIGHT = 5
X_CENTER = 0
Y_CENTER = 0
x_str = input("Enter the x point: ")
y_str = input("Enter the y point: ")
x = float(x_str)
y = float(y_str)
is_in = True
if not (X_CENTER - WIDTH/2 <= x <= X_CENTER + WIDTH/2):
is_in = False
if not (Y_CENTER - HEIGHT/2 <= y <= Y_CENTER + HEIGHT/2):
is_in = False
if is_in:
statement = "is"
else:
statement = "is not"
print("Point (%s, %s) %s in the rectangle." % (x_str, y_str, statement))

Resources