I am currently trying to program a script for my school project. It is supposed to take one pixel from the camera feed and measure at that spot multiple times (for noise cancellation). The part of my code that I am not satisfied with currently looks like this:
canon.ScanXY(x,y)
img_1 = canon.FetchImage(0, 1 * 1)
canon.StopScan()
canon.ScanXY(x,y)
img_2 = canon.FetchImage(0, 1 * 1)
canon.StopScan()
...
canon.ScanXY(x,y)
img_xxx = canon.FetchImage(0, 1 * 1)
canon.StopScan()
The code above will return a string with name img_xxx where xxx stands for a specific number. I was wondering, if there is an easier way to do this. I was trying to loop the function, but was unable to do it so that I have different result from every iteration. And at the end I need to add all of those together in order to create one string from all that were generated before:
img_final = (img_1 + img_2 + img_3 + ... + img_xxx)
and finally to print a Picture out of the result, using
img = np.fromstring(img_final, dtype="uint8").reshape(8,8)
fig, ax = plt.subplots()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.set_xticklabels((0,1))
x=ax.imshow(img,cmap="gray")
The code works, but if I want to change anything, it really takes a lot of time. So far I was working with 64 or less strings, but I want to refine the results, so I would need much more iterations. Any help would be appreciated.
img_final is supposed to be the sum of a sequence of individual img's. The analogy to adding a sequence of integers read from the console would be:
final = int(input("First num: "))
for x in range(xxx-1):
num = int(input("Next num: "))
final += num
Related
I need a loop over all of my clans, which are instances of a class. Each clan needs to be assigned a position, a x and a y coordinate. Preferably as two lists or as a single tuple (but no idea how I specify that). This is how it works for the 1st clan. Afterwards I always have to check, if the position is already assigned. If so, you have to search for a new position until it is free.
I then coded my class like this:
width = 20
height = 20
no_of_clans = 50
import random
class clan:
def __init__(self, index, position_list):
self.index = index
self.position_list = position_list
def index(no_of_clans):
return list(range(1, no_of_clans +1))
def position_list(self):
for i in range(1, no_of_clans +1):
positions = ()
if i ==1: #i can do it either like this
positions = [(random.randint(0, width)), (random.randint(0, height))]
positions.append(x,y)
else: #or like this, I do not know, which one is better, both are running
x = (random.randint(0, width))
y = (random.randint(0, height))
#check if x and y not already used
#assert
positions.append(x,y)
return positions
print(positions)
how can I assign positions randomly when also using 0.5 steps? I always get an error message.
I never get a list of my positions back, but I do not know what I did wrong.
I know those are probably fairly basic questions but I am quite new to python an already searched for 5h today and I really do ot know where to start anymore. I would be really happy if someon could help me. Thank you so much in advance <3
I found the answer to my original question in this post:
Coordinates of the edges of a honeycomb grid in python
Will update if I am finished with the class-thing :)
as a part of my code, I'm trying to get a full factorial matrix, this is not a problem since I already have a working code for it. However, I would like to generalize it in a way that it wouldn't matter the number of inputs. This would require modifying the line:
for combination in itertools.product(X[0,:],X[1,:],X[2,:],X[3,:],X[4,:],X[5,:],X[6,:]):
input_list = dfraw.columns[0:n_inputs]
output_list = dfraw.columns[n_inputs:len(dfraw.columns)]
fflvls = 4
lhspoints = 60000
X = np.zeros((n_inputs, fflvls),float)
ii=0
for entrada in input_list:
X[ii] = np.linspace(min(dfraw[entrada]), max(dfraw[entrada]), fflvls)
ii+=1
number=1
i=0
X_fact=np.zeros((int(fflvls**n_inputs),n_inputs),float)
for combination in itertools.product(X[0,:],X[1,:],X[2,:],X[3,:],X[4,:],X[5,:],X[6,:]):
X_fact[i,:] = (combination)
i +=1
number+=1
I thought of writing the input of itertools.product as a string with a loop and then evaluating but it doesn't work and I've also seen it is regarded as bad practice
prodstring = ['X[0,:]']
for ii in range(n_inputs):
prodstring.append(',X[%d,:]'%(ii))
in_products = ''.join(prodstring)
for combination in itertools.product(eval(in_products)):
X_fact[i,:] = (combination)
i +=1
number+=1
what other way is there to inputing the full range of columns in this function? (or similar ones)
who said working harder is working better? im back from lunch and I delved into *args and **kwargs as a form of procrastination cause ive sometimes seen them mentioned and i was curious. It seems like it was just the tool I needed. In case this can help other code rookies like me in the future:
args = ()
for ii in range(n_inputs):
b = (X[ii,:])
args += (b,)
for combination in itertools.product(*args):
X_fact[i,:] = (combination)
i +=1
number+=1
Seems to work properly. Solved in an hour of "not working" what i haven't solved in approx 4 hours of "working"
I had a test recently (it's over now) and I had this question:
question
and I could do the question. However there was one test case at the end that said that we get an extra 10 marks if the runtime of that case is <1s. However, my issue was that I could not get the runtime to be below 1sec. My code and the test case are below. Also I should add we're not allowed to import any packages.
Test case:
longList = [i for i in range(100000)]
print(calculateAreas(longList,longList[::-1]))
My code:
def calculateAreas(w_list,h_list):
width_length = len(w_list)
height_length = len(h_list)
list_of_areas = []
red_area = 0
white_area = 0
yellow_area = 0
for i in range(width_length):
for n in range(height_length):
if (i+n-2) % 3 == 0:
red_area += (w_list[i] * h_list[n])
if (i+n-2) % 3 == 1:
white_area += (w_list[i] * h_list[n])
if (i+n-2) % 3 == 2:
yellow_area += (w_list[i] * h_list[n])
list_of_areas.insert(0, white_area)
list_of_areas.insert(1, yellow_area)
list_of_areas.insert(2, red_area)
tuple_area = tuple(list_of_areas)
return tuple_area
I would say that the way to speed up is using list comprehension and trying to make only the necessary operations. There is a pattern on the both axis of white -> yellow -> red -> white..., we can use list comprehension to separate these colors and then find the total area of each one of them.
to separate a color in a axis we can use:
list[::3]
so say we could sum up all the white values on the w_list[0] and multiply by the sum of all white values on the h_list[0], we would get about 1/3 of whites total value. So we could repeate this for w_list[1] with h_list[1] and w_list[2] with h_list[2]. In short, what I'm trying to do is separate white with 3 grids like this one
W--W--W-
+--+--+-
+--+--+-
W--W--W-
+--+--+-
slightly dislocated one from the other and using list comprehension to isolate and get the area without having to make nested for loops:
def calculateAreas(w_list, h_list):
white = 0
yellow = 0
red = 0
for i, j in zip([0,1,2], [0,2,1]):
white += sum(w_list[i::3]) * sum(h_list[j::3])
yellow += sum(w_list[i::3]) * sum(h_list[(j+1)%3::3])
red += sum(w_list[i::3]) * sum(h_list[(j+2)%3::3])
return (white, yellow, red)
this way we are only passing 3 times threw the for loop and on a list of 100000 elements it's timing 0.0904s on my slow laptop. If I can give you a couple tips about your code: 1- try to interact directly over the list elements (use enumerate) 2- use 'elif' and 'else' statements (if a color checked 'white', you dont need to check if its red). And in general, if you need to speed up a code, try avoiding nested loops, imagine interacting every element in one list with every other element in another list: thats len(list)**2!
I'm trying to display data from a csv in a text table. I've got to the point where it displays everything that I need, however the table width still has to be set, meaning if the data is longer than the number set then issues begin.
I currently print the table using .format to sort out formatting, is there a way to set the width of the data to a variable that is dependant on the length of the longest piece of data?
for i in range(len(list_l)):
if i == 0:
print(h_dashes)
print('{:^1s}{:^26s}{:^1s}{:^26s}{:^1s}{:^26s}{:^1s}{:^26s}{:^1s}'.format('|', (list_l[i][0].upper()),'|', (list_l[i][1].upper()),'|',(list_l[i][2].upper()),'|', (list_l[i][3].upper()),'|'))
print(h_dashes)
else:
print('{:^1s}{:^26s}{:^1s}{:^26s}{:^1s}{:^26s}{:^1s}{:^26s}{:^1s}'.format('|', list_l[i][0], '|', list_l[i][1], '|', list_l[i][2],'|', list_l[i][3],'|'))
I realise that the code is far from perfect, however I'm still a newbie so it's piecemeal from various tutorials
You can actually use a two-pass approach to first get the correct lengths. As per your example with four fields per line, the following shows the basic idea you can use.
What follows is an example of the two-pass approach, first to get the maximum lengths for each field, the other to do what you're currently doing (with the calculated rather than fixed lengths):
# Can set MINIMUM lengths here if desired, eg: lengths = [10, 0, 41, 7]
lengths = [0] * 4
fmtstr = None
for pass in range(2):
for i in range(len(list_l)):
if pass == 0:
# First pass sets lengths as per data.
for field in range(4):
lengths[field] = max(lengths[field], len(list_l[i][field])
else:
# Second pass prints the data.
# First, set format string if not yet set.
if fmtstr is None:
fmtstr = '|'
for item in lengths:
fmtstr += '{:^%ds}|' % (item)
# Now print item (and header stuff if first item).
if i == 0: print(h_dashes)
print(fmtstr.format(list_l[i][0].upper(), list_l[i][1].upper(), list_l[i][2].upper(), list_l[i][3].upper()))
if i == 0: print(h_dashes)
The construction of the format string is done the first time you process an item in pass two.
It does so by taking a collection like [31,41,59] and giving you the string:
|{:^31s}|{:^41s}|{:^59s}|
There's little point using all those {:^1s} format specifiers when the | is not actually a varying item - you may as well code it directly into the format string.
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