Computing an average based on lists in another function - python

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)

Related

How to replace all elements of a list using a for loop

Question
The question here asks to make two lists/arrays in python and fill it with 0s initially and then occupy them with the relevant values.
import numpy as np
x = []
y = []
for i in range (0,101):
x.append(0)
y.append(0)
xx = np.linspace(1,10,101)
print(xx)
for a in range (len(y)):
for j in xx:
fx = np.log(j)
y[a] = fx
for b in range (len(x)):
for k in xx:
x[b] = k
print(x)
print(" ")
print(y)
I used a nested for loop to traverse through the values in the xx list and used the log function and stored the values in a variable and then replace the 0s in the (y)list with the function values over each iteration. Same thing with the x list but just replace the 0s with the value of the variable which is used in the function respectively.
However the output I keep getting is not right and I can't get what is going wrong within the loops. The output should show the values of x in the first list and the values of f(x) in the second list however it only shows the value of the last x in the range as well as the value of the last f(x) in the range.
Output
I'm guessing you are supposed to use linspace, and enumerate:
import numpy as np
size = 101
x = np.zeros(size)
y = np.zeros(size)
for i, n in enumerate(np.linspace(1,10,size)):
x[i] = n
y[i] = np.log(n)

How do I find the sum of a given list for x[i]≥ a fixed x value, for each x value?

The code block is supposed to do the following:
Find sum(all y_values in the list if the index corresponding to that y value has an x_value which is ≥ a fixed x_value). Find this sum for all x_values in the order given by the list, and append it to a list of its own.
The output should be a list with the same length as len(x_values).
For example:
input:
x_values = [1,2,3,3,4,5]
y_values = [9,4,3,1,2,1]
output should be:
[20,11,7,7,3,1]
Note: I'm using python3.
my_list = []
my_list2 = []
for j in range(len(x_values)):
for i in range(len(x_values)):
if x_values[i] >= x_values[j]: #x_values[j] is supposed to be fixed x_value
my_list.append(y_values[i])
my_list2.append(sum(my_list)) #my_list2 is supposed to be such that len(my_list2)=len(x_values)
You shouldn't be calculating sum(my_list) every time through the inner loop. You should initialize my_list each time through the outer loop, and calculate the sum after the inner loop.
However it can all be replaced with a single list comprehension and a generator in the sum() argument.
Use zip() to loop through x_values and y_values together, to get the y values in the corresponding indexes as the x values that are compared with fixed_x.
result = [sum(y for x, y in zip(x_values, y_values) if x >= fixed_x) for fixed_x in x_values]

Sorting image coordinates in python

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

2 dimensions list (array?) in python

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

Python: inserting a 2D list inside another replacing content

I've written a small (destructive) function that takes two 2D lists (or "grids" as I call them) and a set of coordinates. It inserts the first grid inside the second grid, assumed to be as big or bigger as the first one (no checks implemented). The coordinates denote the top-left corner of the first grid.
def insert_grid(subj, obj, cords=(0, 0)):
u, v = cords
h = len(subj)
w = len(subj[0])
for y in range(0, h):
for x in range(0, w):
obj[u + y][v + x] = subj[y][x]
I was wondering if there was a cleaner, more pythonic way to achieve the same effect. The standard lib methodology would as always be prefered above everything else.
Thank you. Alisa.
You can simplify slightly:
def insert_grid(subj, obj, cords=(0, 0)):
u, v = cords
w = len(subj[0])
for index, row in enumerate(subj, u):
obj[index][v:v+w] = row
This replaces all columns in a row in one go.

Categories