How to output numbers to each iteration in a for loop? - python-3.x

for replay_data in raw_replay_data['data']['video_info']:
target.write("Coordinates: " + replay_data['lat'] + (',') + replay_data['lnt'] + "\n")
This for loop gives me fx. the output of:
Coordinates: 0,0
Coordinates: 0,0
Coordinates: 0,0
Coordinates: 0,0
I would like a number after each "Coordinates" string that increases for each new coordinates available.
How can I make it output:
Coordinates 1: 0,0
Coordinates 2: 0,0
Coordinates 3: 0,0
Coordinates 4: 0,0

Look up the enumerate() function, it's your best friend in for loops. Also you can use some str.format() function to make your output more readable:
for index, replay_data in enumerate(raw_replay_data['data']['video_info']):
target.write("Coordinates {0}: {1}, {2}\n".format(index+1, replay_data['lat'], replay_data['lnt'])

You create a counter and count up:
numbr = 1 # counter, starting at 1
for replay_data in raw_replay_data['data']['video_info']:
target.write("Coordinates " + str(numbr) + ": " + replay_data['lat'] + (',') + replay_data['lnt'] + "\n")
numbr += 1 # increment counter
You might want to look into string format methods: string.format
You can do things like:
replay_data = {}
replay_data['lat'] = 1
replay_data['lnt'] = 2
numbr = 22
print("Coordinates {n}: {lat},{lng}\n"
.format(n=numbr, lat = replay_data['lat'], lng = replay_data['lnt']))
Output:
Coordinates 22: 1,2

Related

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

Printing a hollow circle using asterisks (so no turtle)

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))

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

How to add consistent arrow for a set of curve with gnuplot

I want to add arrow for a series of curves in gnuplot. The question is how to put arrow in the center of a curve. My solution is to find line segment in the points sequence, and draw an arrow for this line segment. It works but the size of arrows are different.
I have write a code with python+gnuplot, it works but looks ugly
#!/bin/python
import numpy as np
import Gnuplot
def middleArrowCurve(g, x,y, percent, reverse=False):
d = Gnuplot.Data(x,y,with_='l')
index = int(len(x)*percent)
fromx,tox = x[index],x[index+1]
fromy,toy = y[index],y[index+1]
g('set style arrow 1 front head filled size screen 0.03,15 lt 1 lw 1')
if reverse:
g('set arrow from ' + str(tox) + ',' + str(toy) + ' to ' + str(fromx) + ',' + str(fromy) + ' as 1')
else :
g('set arrow from ' + str(fromx) + ',' + str(fromy) + ' to ' + str(tox) + ',' + str(toy) + ' as 1')
return d
def stableNode2():
g = Gnuplot.Gnuplot(persist=1)
g('set term png')
g('set output "stableNode2.png"')
g('unset key')
g('unset tics')
g('unset border')
g('set xrange [-1:1]')
g('set yrange [-1:1]')
data = []
reverse = False
for s in [-1,1]:
x = np.linspace(s,0,20)
data.append(middleArrowCurve(g,x,0.6*x**2,0.5,reverse))
data.append(middleArrowCurve(g,x,-0.6*x**2,0.5,reverse))
data.append(middleArrowCurve(g,x,2*x**2,0.5,reverse))
data.append(middleArrowCurve(g,x,-2*x**2,0.5,reverse))
data.append(middleArrowCurve(g,x,x*0,0.5,reverse))
data.append(middleArrowCurve(g,x*0,x,0.5,reverse))
g.plot(*data)
stableNode2()
As of version 4.6 gnuplot automatically scales the arrow head if the arrow length is less than twice the head's length. In version 5.0 (almost stable, 5.0RC2 is out) an additional arrow parameter fixed was introduced which prevents this scaling. So using the line
g('set style arrow 1 front head filled size screen 0.03,15 fixed lt 1 lw 1')
gives the result:
In version 4.6 I don't know any other workaround than increasing the length of some arrows.
Use set object poly can solve this.
#!/bin/python
import numpy as np
import Gnuplot
arrowCount = 0
def addArrow(g, x,y, dx, dy, width=0.01,angle=15):
def normal(v):
s = 1.0/np.sqrt(v[0]**2+v[1]**2)
v[0] *= s
v[1] *= s
l = [dx,dy]
n = [-dy,dx]
normal(l)
normal(n)
length = width/np.tan(angle*np.pi/360)
coords = []
coords.append((x,y))
coords.append((x+n[0]*width,y+n[1]*width))
coords.append((x+l[0]*length,y+l[1]*length))
coords.append((x-n[0]*width,y-n[1]*width))
coords.append((x,y))
coordsStr = "from "
coordsStr += " to ".join([str(c[0])+","+str(c[1]) for c in coords])
global arrowCount
arrowCount += 1
return 'set object ' + str(arrowCount) + ' polygon ' + coordsStr + ';set object ' + str(arrowCount) + ' fc rgb "red" fs solid '
def middleArrowCurve(g, x,y, percent, reverse=False):
d = Gnuplot.Data(x,y,with_='l')
index = int(len(x)*percent)
fromx,tox = x[index],x[index+1]
fromy,toy = y[index],y[index+1]
if reverse:
return d,addArrow(g, tox,toy, -tox+fromx, -toy+fromy)
else:
return d,addArrow(g, fromx,fromy, tox-fromx, toy-fromy)
def stableNode2():
g = Gnuplot.Gnuplot(persist=1)
g('set term png')
g('set output "stableNode2.png"')
g('unset key')
g('unset tics')
g('unset border')
g('set xrange [-1:1]')
g('set yrange [-1:1]')
data = []
reverse = False
for s in [-1,1]:
x = np.linspace(s,0,20)
data.append(middleArrowCurve(g,x,0.6*x**2,0.5,reverse))
data.append(middleArrowCurve(g,x,-0.6*x**2,0.5,reverse))
data.append(middleArrowCurve(g,x,2*x**2,0.5,reverse))
data.append(middleArrowCurve(g,x,-2*x**2,0.5,reverse))
data.append(middleArrowCurve(g,x,x*0,0.5,reverse))
data.append(middleArrowCurve(g,x*0,x,0.5,reverse))
for a in data:
g(a[1])
g.plot(*[d[0] for d in data])
stableNode2()
The remaining problem is why the polygon arrows are covered by line plot? If I put polygon drawing after the line plot, they are just ignored.

d3 path radius calculation for quarter circle

I'd like to draw a path between two points, which has a quarter circle arc where the arc radius = x2-x1.
For example:
x1=100
y1=100
x2=300
y2=300
I am using:
dx = x2-x1,
dy = y2-y1,
dr = Math.sqrt(dx*dx+dy*dy);
return "M" + x1 + "," + y1 + "A" + dr + "," + dr + " 0 0,1 " + x2 + "," + y2;
I am struggling to calculate the correct dr for the quarter circle radius.
Thanks
In this case, the line connecting your two points would be the hypotenuse of your triangle. The other sides would have the same length, i.e. the radius. You can calculate it like this:
var dr = Math.sqrt((dx*dx+dy*dy)/2);
Full example: http://jsfiddle.net/E7JPy/1/

Resources