I want to sort four co-ordinates, for example- (180,120),(100,40),(100,120),(180,40). This co-ordinates will be returned in random order by the code. I want to sort these co-ordinates such that I have tuple in the following order - ((100,40),(100,120),(180,40),(180,120)). How I can achieve this in python?
One more set of co-ordinates are (170,118),(90,44),(80,120),(165,39)
I think you can just sort based on X axis, then Y axis if X axes are equal,
Maybe something like this?:
Points = [(180,120),(100,40),(100,120),(180,40)];
def Swap(Array, Index1, Index2):
Temp = Array[Index1];
Array[Index1] = Array[Index2];
Array[Index2] = Temp;
def Sort(Array):
for x in range(0, len(Array) - 1):
if (Array[x][0] > Array[x+1][0]):
Swap(Array, x, x+1);
elif (Array[x][0] == Array[x+1][0]):
if (Array[x][1] > Array[x+1][1]):
Swap(Array, x, x+1);
Aight I did not know you could just call sorted() as shown by mozway, that is very convenient
Related
I am using a large data set (approx 3600 x values & 3600 y values), and am trying to return the position of certain x values corresponding to y values that have already been pulled out of the original data.
for n in new_y:
if new_y in y:
new_x.append(index(y))
print(new_x)
The error code I get states:
:43: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
if new_y in y:
Edit: I should have mentioned that when printing new_x, an empty list is returned ([])
You should use enumerate:
new_x = []
for i, n in enumerate(new_y):
if n in y:
new_x.append(i)
print(new_x)
Or, more succinctly:
new_x = [i for i, n in enumerate(new_y) if n in y]
Use numpy library that way you can slice the data wihtout iterating through the "dataset".
So I need to generate a mean for both the list of x coordinates and the list of y coordinates from one function using another function, but I'm not exactly sure how to do so. Here's what I've got so far, the first function is correct, it's just the second one that needs work, I'm just not sure what to do. 'datafile1' is simply a list of x and y coordinates separated by a tab. I should mention that this has to be done through a separate function, otherwise I would have just done this in a more simpler way.
import math
import statistics
def fileRead():
"Reads the input file and stores the x and y coordinates in a parallel list"
dataFile = open('datafile1.txt', 'r')
dataList = [] # list comprised of x and y pairs
x = [] # list comprised of just x coordinates
y = [] # list comprised of just y coordinates
for dataLine in dataFile:
dataList.append(dataLine)
dataSplit = dataLine.split()
x.append(float(dataSplit[0]))
y.append(float(dataSplit[1]))
return x, y
def getMean(dataList):
"Computes the mean of the data set"
dataMean = statistics.mean(dataList)
return dataMean
Since calculating the mean isn't exactly complex (it's just a function call), why don't you just calculate it inline right after calling fileRead()?
(x, y) = fileRead()
xMean = statistics.mean(x)
yMean = statistics.mean(y)
I have to create 2 functions that involve a 2 dimension list in order to make a grid for a basic Python game :
The first function must take in parameter an int n and return a list of 2 dimensions with n columns and n lines with all values to 0.
The second one must take a 2 dimension list in parameter and print the grid but return nothing.
Here is what I came with:
def twoDList(x, y):
arr = [[x for x in range(6)] for y in range(6)] # x = height and y = width
return arr
def displayGrid(arr):
for i in range(0, 5):
print(arr[i][i])
Could you please help me to improve the code regarding the instructions and help me to understand how to display the whole grid with the code please?
Here are 2 methods using no 3rd party libraries.
One simple way to create a 2D array is to keep appending an array to an array:
for x in range(10): #width
for y in range(10): #height
a.append(y) #you can also append other data is you want it to be empty, this just makes it 0-9
arr.append(a) #add the 1-9
a = [] #clear the inner array
Here, I re-created the same array (a) 10 times, so it's kind of inefficient, but the point is that you can use the same structure with custom data input to make your own 2D array.
Another way to get the exact same 2D array is list comprehension
arr = [[x for x in range(10)] for y in range(10)]
This is probably what you were trying to do with the code you provided, which is, as mentioned in the comments, syntactically incorrect.
To print, just tweak the code you have to have 2 loops: one for x and one for y:
for x in range(5):
for y in range(5):
print(arr[x][y])
I still see erros in your code:
In your first function, since x,y are your inputs, you want to USE them in your list comprehension. You're not using them in your code
def twoDList(x, y):
arr = [[x for x in range(6)] for y in range(6)] # x = height and y = width
return arr
In your example, no matter what the value of x or y is, you're getting a 6x6 grid. You want to use x and y and replace the fixed values you have over there (HINT: change your '6').
Won't do that for you,
In your print function, you might want to use two variables, once per each dimension, to use as indexes.
Also, don't use fixed values in here, get them from your input (i'm guessing this is homework, so won't put the whole code)
def displayGrid(arr):
for i in range(0, 5):
for j in range(0, 5):
print(arr[i][j])
I have a list-of-list-of-lists, where the first two act as a "matrix", where I can access the third list as
list3 = m[x][y]
and the third list contains a mix of strings and numbers, but each list has the same size & structure. Let's call a specific entry in this list The Number of Interest. This number always has the same index in this list!
What's the fastest way to get the 'coordinates' (x,y) for the list that has the largest Number of Interest in Python?
Thank you!
(So really, I'm trying to pick the largest number in m[x][y][k] where k is fixed, for all x & y, and 'know' what its address is)
max((cell[k], x, y)
for (y, row) in enumerate(m)
for (x, cell) in enumerate(row))[1:]
Also, you can assign the result directly to a couple of variables:
(_, x, y) = max((cell[k], x, y)
for (y, row) in enumerate(m)
for (x, cell) in enumerate(row))
This is O(n2), btw.
import itertools
indexes = itertools.product( xrange(len(m)), xrange(len(m[0]))
print max(indexes, key = lambda x: m[x[0]][x[1]][k])
or using numpy
import numpy
data = numpy.array(m)
print numpy.argmax(m[:,:,k])
In you are interested in speeding up operations in python, you really need to look at numpy.
Assuming "The Number of Interest" is in a known spot in the list, and there will be a nonzero maximum,
maxCoords = [-1, -1]
maxNumOfInterest = -1
rowIndex = 0
for row in m:
colIndex = 0
for entry in row:
if entry[indexOfNum] > maxNumOfInterest:
maxNumOfInterest = entry[indexOfNum]
maxCoords = [rowIndex,colIndex]
colIndex += 1
rowIndex += 1
Is a naive method that will be O(n2) on the size of the matrix. Since you have to check every element, this is the fastest solution possible.
#Marcelo's method is more succulent, but perhaps less readable.
How do I get a tuple/list element given a condition in python?
This occurs pretty often and I am looking for a nice-few-lines-pythonic way of doing this.
here could be an example:
Consider a tuple containing 2D points coordinates like this:
points = [[x1, y1],[x2, y2],[x3, y3], ...]
And I would like to get the point that minimizes the euclidean distance given an arbitrary point (say [X, Y] for instance, my point is : it is not contained in the list!)
def dist(p1, p2):
return sqrt((p2[0]-p1[0])**2+(p2[1]-p1[1])**2)
pointToCompare2 = [X, Y]
Anyone having a freaky one liner(or not) for that?
Thanks!
min(points, key=lambda x: dist(pointToCompare2, x))
min is a built-in function.
v = [1,3,2,4,7,3,3,4,5,11]
def get_num_uniques(v):
count = []
dup = []
tmp = []
for i in v:
if i not in count:
count.append(i)
else:
dup.append(i)
count.remove(i)
for j in count:
if j not in dup:
tmp.append(j)
return tmp
#Call the function
print get_num_uniques(v)