I am receiving Points in large number from a sensor in real-time. However, I just need 4 categories of points, i.e., top_left, top_right, bottom_left, and bottom_right. I have an if-elif statement in Python 2 as follows:  from random import random, randint  # points below are received from sensor. however,  # here in this post I am creating it randomly. points = [Point(randint(0, i), random(), random(), random()) for i in range(100)]   # 4 categories top_left, top_right, bottom_left, bottom_right = None, None, None, None for p in points:     if p.id == 5:         top_left = p     elif p.id == 7:         top_right = p     elif p.id == 13:         bottom_left = p     elif p.id == 15:         bottom_right = p  print top_left.id, top_left.x, top_left.y, top_left.z # check variable   Each Point has an id and x, y, z parameters. This is an inbuilt class. I am just showing a sample class here.   class Point():     def __init__(self, id, x, y, z):         self.id = id         self.x = x         self.y = y         self.z = z   Is there any efficient way considering runtime of achieving the same.  Answer: I am adding the results which I got from the answers. It seems that  is fastest among all. Below is my test code:  class Point():     def __init__(self, id, x, y, z):         self.id = id         self.x = x         self.y = y         self.z = z  from random import random, randint n = 1000 points = [Point(randint(0, i), random(), random(), random()) for i in range(n)]  def method1():     top_left, top_right, bottom_left, bottom_right = None, None, None, None     for p in points:         if p.id == 5:             top_left = p         elif p.id == 7:             top_right = p         elif p.id == 13:             bottom_left = p         elif p.id == 15:             bottom_right = p     #print top_left.id, top_left.x, top_left.y, top_left.z  def method2():     categories = {         5: None,  # top_left         7: None,  # top_right         13: None,  # bottom_left         15: None  # bottom_right     }      for p in points:         categories[p.id] = p      top_left = categories[5]     #print top_left.id, top_left.x, top_left.y, top_left.z  def method3():     name_to_id = {'top_left': 5, 'top_right': 7, 'bottom_left': 13, 'bottom_right': 15}     ids = [value for value in name_to_id.values()]     bbox = {id: None for id in ids}      for point in points:         try:             bbox[point.id] = Point(point.id, point.x, point.y, point.z)         except KeyError:  # Not an id of interest.             pass      top_left = bbox[name_to_id['top_left']]     #print top_left.id, top_left.x, top_left.y, top_left.z  from timeit import Timer print 'method 1:', Timer(lambda: method1()).timeit(number=n) print 'method 2:', Timer(lambda: method2()).timeit(number=n) print 'method 3:', Timer(lambda: method3()).timeit(number=n)   See Below the returned output:  ravi@home:~/Desktop$ python test.py  method 1: 0.174991846085 method 2: 0.0743980407715 method 3: 0.582262039185
5832
I want to write a function in Python that returns different fixed values based on the value of an input index.    In other languages I would use a switch or case statement, but Python does not appear to have a switch statement.  What are the recommended Python solutions in this scenario?
92159
I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:  Random.nextInt(74)   I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.
88774
How do I summon arrows from the sky in a random position but at the same time to be inside the coordinates that I want?  For example, if I use the following, will that summon an arrow in that position?  /summon Arrow x y z   I want it to be summoned in a random X, Y, Z but at the same time within a specific position of four points:  {x1,y1,z1} &amp; {x2,y2,z2} &amp; {x3,y3,z3} &amp; {x4,y4,z4}   How could I do this?
46866
Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about  for i in range(0, 20): for i in xrange(0, 20):
59672
I want to randomly generate reachable platforms on the fly for a 2D game.  Right now, I am just creating platforms at random x,y positions.  Only 4 platforms can exist at once, so once the 5th one is generated the 1st one is removed (fifo).  So, I want to ensure that the player can jump from his current platform to at least one other at any given time.  I was thinking of using some variant of the distance formula to calculate the location of the next platform being generated.  I was hoping someone could help me out with the formula for calculating the next platforms possible x,y positions.  The player variables I am assuming will be important are speedX, speedY, and gravity.  From here, I should be able to calculate the maximum distance to plug into the distance formula.    However, I am thinking that some variation of the distance formula that contains a variable for slope would be better in my case.  I want to ensure that the player will never get stuck on a platform with no where it can jump.  Also, I want to ensure that platforms aren't generated on top of each other.  Formulas/images/code are a huge plus.  Here is how jumping is currently working.  Field speedY:Float = 4 Field GRAVITY:Float = .05  Method Update:Void()     If KeyDown(KEY_SPACE) And not jumping Then         dy=-speedY         jumping = true     EndIf       If jumping         dy += GRAVITY         local tempY:Float = y + dy         y = tempy     Endif End Method   Edit: I now understand that the formula is just the displacement of basic projectile motion.     Except, in my case, we don't care about cos/sin because the angle will always be the same.
83200
Given: A list of integers is there.Now there are 2 buckets -bucket A and bucket B.This step is repeated as  long as there are numbers left in the list.Integers from start or end of the list are removed from the list and added to bucket A. The probability of picking a number from the start or the end is equal to 0.20 . Then similarly,the next number picked from start or the end is added to B. Then to A and so on.  Required: Expected values in Bucket A and Bucket B.  Eg  1 ,2m3   1 or 8 can be added to bucket A. 1) 1-&gt; 4 or 8 can be added to B.    a)B picks 4 -&gt; A picks 8    b)B picks 8-&gt;  A picks 4 2) 8-&gt; 1 or 4 can be added to B.    a)B picks 1 -&gt;A picks 4    b)B picks 4 -&gt;A picks 1 So E(A)=(((8+4)/2+1)+((4+1)/2+8))/2=8.25    I tried to get a general formula for E(A) and E(B) .I was getting a tree structure with 2^n-1 nodes but I wasn't able to derive a specific formula. Can anyone derive this? I tried for a general list a,b,c,d  having 4 integers.  E(A)=1/4((c+d)/2+b)+((b+c)/2+d))+a/2+1/4((b+c)/2+a+c+(b+a)/2)+d/2   Also,clearly the problem is symmetrical from both ends of the list.That is coefficient of a and d is same, b and c is same in E(A) Can anyone simplify this for any general list having m numbers?
11676
I have a script, which creates multiple objects through a loop. However, the script freezes the viewport until it is done. Instead, I would like every object to be seen in the viewport one by one as it is created.   In its simplest terms:  import bpy import random for i in range(1000):     XYZcoord = (random.random()*100, random.random()*100, random.random()*100)     bpy.ops.mesh.primitive_uv_sphere_add(location=XYZcoord)     # Update the viewport here.   Is there a way to update the viewport after every iteration of the loop to see every newly added object as they are created? Or do I need to use a different method?
78046
My eventual goal is to automate kernel density calculations for a large corpus of point data; however, if all points are identical (for example, if there are 7 points all stacked on top of one another because they have the same long/lat values), the  in arcpy will not work. It will result in the following error:  "Error 010246: All input points are identical A valid window must be specified"   Since this will be an automated process, I need a way to check the points in the current input to be sure they aren't all the same using python/arcpy. Is there a way to do that?   EDIT: I specified a grid size and an extent, so a lot of the errors are fixed; however, identical points still give me the "valid window must be specified." I have tried to use the FindIdentical function to look for identical points, but this returns a DBF file, that I cannot read in the script. Is there some way to read a DBF easily in python, or can I find if all points are identical in another way?
115683
Let me describe the data setup. A line has been provided as an array of coordinate pairs, one for each vertex. This array is variable in size, anywhere from 2 to 200 coordinate pairs per line. What I am trying to wrap my mind around is the best way to create these lines. Arcpy and ArcObjects are both viable options, but ArcObjects is preferred due to its speed (generally).   I have brainstormed a few methods, but they fall short for some reason or another:  1) I could use the  with arcpy to create polylines and then Copy Features, but the resulting geometry would not have any of the attribution necessary to identify said points.  2) I could use , but this only works with one pair of point, and I require something much more robust.  The long and short is that I require a method that can create a polyline from arrays and maintain a schema for data that I have created in a table. One idea I have is to create said table and schema, and then somehow create the polyline and copy its shape property to the output table, porting over the ID and whatever other attribution is needed. How can I go about creating the polyline's shape property without resorting to an intermediate shapefile? Or, if there is a better method that comes to mind, please share it with me.  Update This code seems to work!  IFeatureClass fClass = gpUtil.OpenFeatureClassFromString(path); IFeatureCursor cursor = fClass.Insert(true); IFeatureBuffer buffer = fClass.CreateFeatureBuffer();  &lt;snip...&gt;  string[] nodearray = a.Split(';'); foreach (string i in nodearray) {     query.WhereClause = "\"PNT_ID\" = '" + i+"'";     Console.WriteLine(query.WhereClause.ToString());     ICursor search = table.Search(query, false);     IRow row = search.NextRow();     float x = float.Parse(row.get_Value(2).ToString());     float y = float.Parse(row.get_Value(3).ToString());     int id = int.Parse(row.get_Value(1).ToString());     point.X = x;     point.Y = y;     point.ID = id;     point.SpatialReference = sRef;     pCollection.AddPoint(point, ref Missing, ref Missing);  } IGeometry5 polygeo = (IGeometry5)pCollection; buffer.set_Value(1, polygeo); buffer.set_Value(2, wayid); cursor.InsertFeature(buffer);
12368
I need to use a priority queue in my Python code, and:   am looking for any fast implementations for priority queues optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).   Looking around for something efficient, I came upon , but:   I'm looking for something faster than heapq, which is implemented in native Python, so it's not fast. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs.  Update: Re comparison in heapq, I can either use a (priority, object) as Charlie Martin suggests, or just implement __cmp__ for my object.
23692
Consider a game where one would roll a random integer between $1$ and $N_0$ where $N_0 \ge 1$. The newly randomly generated number is now the new &quot;upper limit&quot; of the game, the game continues by rolling a random number between $1$ and the randomly generated number. This game continues until the randomly generated number is 1. Here is an example of how it can look like. Consider $N_0 = 1000$ $$N_1 = Random(1, N_0) = Random(1, 1000) = 623$$ $$N_2 = Random(1, N_1) = Random(1, 623) = 366$$ $$N_3 = Random(1, N_2) = Random(1, 366) = 303$$ $$N_4 = Random(1, N_3) = Random(1, 303) = 190$$ $$N_5 = Random(1, N_4) = Random(1, 190) = 52$$ $$N_6 = Random(1, N_5) = Random(1, 52) = 13$$ $$N_7 = Random(1, N_6) = Random(1, 13) = 1$$ $$END$$ The Length of the example game was 7, it took 7 rolls to reach 1. Given the Starting Upper Limit $N_0$, what is the average amount of rolls needed to reach 1? I have tried to write Python code to help with this problem and it seems this follows a Logarithmic Pattern with the function to approximate the amount is $f(N_0) = 1.0168287465013466\ln(N_0) + 1.4731706151125865$
113501
I'd like to find the min/max boundaries of a sliding window of minimum size that contains a certain fraction of the total number of elements in an array or collection of numbers.   Example: taking integers to make it easier to explain, say the proportion of elements that we're looking for is 50% on this array:  [1,1,2,3,3,3,3,3,3,4,5,6,7,8,9,10]  The mystery function would return something like ( 2, 4 ), meaning that the minimum value is 2 and the max value is 4 (let's assume it's inclusive and note that these are VALUES, not indices). That little window contains 8 of the 16 values and it's only 2 units wide, the narrowest such window that contains half the number of values.  Note: the quartiles are [1,1,2,3], [3,3,3,3], [3,4,5,6], [7,8,9,10] so they are NOT what I'm looking for.  I can code it...may take some time to get it nice. Hopefully somebody has run across it before. Does it have a name?  Is there an existing method that somebody knows about?  I am interested in Python implementations.   UPDATE:  Thanks to Glen_b who gave the names 'short-half' and 'shortest interval' I was able to come up with this:
16381
I would want to do something like:  &gt;&gt;&gt; lst = [1, 2, 3, 4, 5] &gt;&gt;&gt; lst.find(lambda x: x % 2 == 0) 2 &gt;&gt;&gt; lst.findall(lambda x: x % 2 == 0) [2, 4]   Is there anything nearing such behavior in Python's standard libraries?  I know it's very easy to roll-your-own here, but I'm looking for a more standard way.
45380
I have a box bounded by min_x, min_y, max_x, max_y, I also have a multipolygon = poly contained in that box. I'm trying to equidistantly scatter points throughout that box, outside of that multipolygon, for the eventual purpose of using a modified A* algorithm to find a route between two points. Right now, I can generate points as such: from shapely.geometry import Point x_range = np.linspace(min_y,max_y,round((max_y - min_y)*2.5),False) y_range = np.linspace(min_x,max_x,round((max_x - min_x)*2.5),False) points = [] point_dict = dict() i = 0 for x in x_range:     j = 0     for y in y_range:         p = Point(y,x)         if not poly.contains(p):             points.append(p)             point_dict[i,j] = p         j+=1     i+=1  They're in an x-y grid along the map, but I think a more efficient way to generate points for a path would be to create this grid then add a repulsion factor so they're all pushed away from each other inversely proportional to their distance from one another AND from the multipolygon and the bounding box. Eventually I imagine this would end up in some solid state equilibrium. Right now I maintain a list of reference for each of the 8 nearest points to each point as follows: edge_list = [] for point in point_dict:     for i in [point[0]-1, point[0], point[0]+1,point[0]+2,point[0]-2]:         for j in [point[1]-1, point[1], point[1]+1,point[1]+2,point[1]-2]:             try: #we already excluded points s.t. poly.contains(point)                 if not point_dict[point].distance(point_dict[i,j]) == 0:                     edge_list.append([point, (i,j), point_dict[point].distance(point_dict[i,j])])             except:                 pass             j+=1         i+=1  Right now I use this edge list so that I can construct a graph and run djikstra's algorithm on it. By constraining it to the &lt;= 8 nearest points, I reduce the number of edges that need to be checked foreach point. My problem here is two-fold:  I have little idea how I would accomplish this repulsion addition computationally I don't know how I would maintain a reference for the n-nearest points to each point after the equilibrium is reached.
23996
I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:  &gt;&gt;&gt; s = 'spam' &gt;&gt;&gt; s[:-1] 'spa'   Why does slicing with no beginning bound and a '-1' return every element except the last one? Is calling s[0:-1] logically the same as calling s[:-1]? They both return the same result. But I'm not sure what python is doing exactly. Any help would be greatly appreciated.
120783
This is what I have so far:    myArray.map!{ rand(max) }   Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers?  Edit: I'd really like to see this done w/o loop - if at all possible.
103588
In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:  "[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"   Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:  print 'my list is %s'%(list)   it looks something like this:  [&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;]   how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?