calculation of variance function equation - statistics

I have an error in this code as I want to calculate the variance between the values in the(x1) and (x2) list. any recommendation?!
def my_var(L):
s = 0
t = 0
u = 0
for i in range(0, len(L)):
s += L[i]
t = s/len(L)
u += ((L[i]-t)*(L[i]-t))
return u / len(L)
x1 = [1, 3, 4, -3, 8]
x2 = [1, -4, 7, 2]
v1 = my_var(x1)
v2 = my_var(x2)
print(v1)
print(v2)

You're doing many things incorrectly based on how I learned prob and stats. You need to calculate the average (mean) and then sum each value subtracted by the mean, squared. Then finally take that numerator and divide by 1 less than the sample size (n-1).
def my_var(L):
mean = float(sum(L) / Len(L))
numerator = 0
for i in range(0, len(L)):
numerator += (L[i]-mean)**2
return numerator / (len(L) - 1)
x1 = [1, 3, 4, -3, 8]
x2 = [1, -4, 7, 2]
v1 = my_var(x1)
v2 = my_var(x2)
print(v1)
print(v2)
Without using sum:
def my_var(L):
my_sum = 0
mean = 0
numerator = 0
for i in range(0, len(L)):
my_sum += L[i]
mean = float(my_sum / len(L))
for i in range(0, len(L)):
numerator += (L[i]-mean)**2
return numerator / (len(L) - 1)
x1 = [1, 3, 4, -3, 8]
x2 = [1, -4, 7, 2]
v1 = my_var(x1)
v2 = my_var(x2)
print(v1)
print(v2)

Try numpy.
import numpy as np
x1 = [1, 3, 4, -3, 8]
x2 = [1, -4, 7, 2]
v1 = np.var(x1)
v2 = np.var(x2)

Thank you #billy_ferguson. I have modified your code and it works. Execuse me, I am still an amateur but could you replace float and sum function and use simpler arithmetic operators as len(L) and += in this line mean = float(sum(L) / len(L))
def my_var(L):
mean = 0
numerator = 0
for i in range(0, len(L)):
mean = float(sum(L) / len(L))
numerator += (L[i]-mean)**2
return numerator / len(L)
x1 = [1, 3, 4, -3, 8]
x2 = [1, -4, 7, 2]
v1 = my_var(x1)
v2 = my_var(x2)
print(v1)
print(v2)

Related

I want to print all pairs with given sum k

def printPairs(arr, n, sum):
for i in range(0, n ):
for j in range(i + 1, n ):
if (arr[i] + arr[j] == sum):
print("(", arr[i], ", ", arr[j], ")", sep = "")
# Driver Code
arr = [1, 5, 7, -1, 5]
n = len(arr)
sum = 6
printPairs(arr, n, sum)
Does this look like it will do the job for you?
def printPairs (array, total) :
used = []
for number1 in array :
for number2 in array :
if number1 + number2 == total and number2 not in used :
print (f'({number1}, {number2})')
used.extend ([number1, number2])
test_array = [1, 5, 7, -1, 5]
# test_array = [4, 2, 1, 3, 6]
target = 6
printPairs (test_array, target)

Remove non-conjugates from complex numbers list

I have two lists, one contains the real part of imaginary numbers, the other contains the imaginary part of the same numbers. I want to remove from both lists the imaginary numbers that do not have a conjugate.
For example, the following lists x = [3, 4, 2, 7, 4] and y = [2, -1, 0, 6, 1] represent the numbers :
3 + 2j <- no conjugate (to remove)
4 - 1j <- conjugate (to keep)
2 + 0j <- real (to keep)
4 + 1j <- conjugate (to keep)
7 + 6j <- no conjugate (to remove)
The expected result is the following :
new_x = [4, 2, 4]
new_y = [-1, 0, 1]
Any idea how i can achieve this ? Thanks
This script will find complex conjugates from lists x and y:
x = [3, 4, 2, 7, 4]
y = [2, -1, 0, 6, 1]
tmp = {}
for r, i in zip(x, y):
tmp.setdefault(i, set()).add(r)
x_out, y_out = [], []
for r, i in zip(x, y):
if i==0 or r in tmp.get(-i, []):
x_out.append(r)
y_out.append(i)
print(x_out)
print(y_out)
Prints:
[4, 2, 4]
[-1, 0, 1]

Finding maximal submatrix of all 1's - missing argument error

Program that finds the maximal rectangle containing only 1's of a binary matrix with the maximal histogram problem.
I am trying to do some tests on a code
def maximalRectangle(self, matrix):
if not matrix or not matrix[0]:
return 0
n = len(matrix[0])
height = [0] * (n + 1)
ans = 0
for row in matrix:
for i in range(n):
height[i] = height[i] + 1 if row[i] == '1' else 0
stack = [-1]
for i in range(n + 1):
while height[i] < height[stack[-1]]:
h = height[stack.pop()]
w = i - 1 - stack[-1]
ans = max(ans, h * w)
stack.append(i)
return ans
# Driver Code
if __name__ == '__main__':
matrix = [[0, 1, 0, 1],
[0, 1, 0, 1],
[0, 1, 1, 1],
[1, 1, 1, 1]]
print(maximalRectangle(matrix))
I get TypeError: maximalRectangle() missing 1 required positional argument: 'matrix' error
Solved by removing self and changing the print statement to:
print(maximalRectangle([
["1","0","1","0","0"],
["1","1","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]]))

Compute distance metric in a complete graph

Suppose I have an array, namely Map. Map[i][j] means the distance between area i and area j. Under this definition, we get:
a) Map[i][i] always equals 0.
b) Map[i][k] <= Map[i][j] + Map[j][k] for all i,j,k
I want to build a function func(Map,k) returning a metric D, while D[i][j] is the shortest distance of a route from area i to area j, and this route should pass through at least k different area.
This is my python code to do so:
def func(Map,k):
n=len(Map)
D_temp = [list(x) for x in Map]
D = [list(x) for x in Map]
for m in range(k - 1):
for i in range(n):
for j in range(n):
tmp = [D[i][x] + Map[x][j] for x in range(n) if x != i and x != j]
D_temp[i][j] = min(tmp)
D = [list(x) for x in D_temp]
return D
func([[0, 2, 3], [2, 0, 1], [3, 1, 0]],2)
return a distance metric D which equals [[4, 4, 3], [4, 2, 5], [3, 5, 2]]
D[0][0] equals 4, because the shortest route from area0 to area0 which pass through at least 2 area is {area0-->area1-->area0}, and the distance of the route is Map[0][1]+Map[1][0]=2+2=4
Wanted to know what would be the best way to do that?
You can use the A* algorithm for this, using Map[i][j] as the heuristic for the minimum remaining distance to the target node (assuming that, as you said, Map[i][j] <= Map[i][x] + Map[x][j] for all i,j,x). The only difference to a regular A* would be that you only accept paths if they have a minimum length of k.
import heapq
def min_path(Map, k, i, j):
heap = [(0, 0, i, [])]
while heap:
_, cost, cur, path = heapq.heappop(heap)
if cur == j and len(path) >= k:
return cost
for other in range(len(Map)):
if other != cur:
c = cost + Map[cur][other]
heapq.heappush(heap, (c + Map[other][j], c, other, path + [other]))
Change your func to return a list comprehension using this min_path accordingly.
def func(Map, k):
n = len(Map)
return [[min_path(Map, k, i, j) for i in range(n)] for j in range(n)]
res = func([[0, 2, 3], [2, 0, 1], [3, 1, 0]], 2)
This gives me the result [[4, 4, 3], [4, 2, 3], [3, 3, 2]] for len(path) >= k, or [[4, 4, 3], [4, 2, 5], [3, 5, 2]] for len(path) == k.

Dynamic Programming: Tabulation of a Recursive Relation

The following recursive relation solves a variation of the coin exchange problem. Count the number of ways in which we can sum to a required value, while keeping the number of summands even:
def count_even(coins, num_coins, req_sum, parity):
if req_sum < 0:
return 0
if req_sum == 0 and not parity:
return 1
if req_sum == 0 and parity:
return 0
if num_coins == 0:
return 0
count_wout_high_coin = count_even(coins, num_coins - 1, req_sum, parity)
count_with_high_coin = count_even(coins, num_coins, req_sum - coins[num_coins - 1], not parity)
return count_wout_high_coin + count_with_high_coin
This code would yield the required solution if called with parity = False.
I am having issues implementing a tabulation technique to optimize this algorithm. On a first attempt I tried to follow the same pattern as for other DP problems, and took the parity as another parameter to the problem, so I coded this triple loop:
def count_even_tabulation(S, m, n):
if m <= 0 or n < 0:
return 0
if n == 0:
return 1
table = [[[0 for x in range(m)] for x in range(n + 1)] for x in range(2)]
for j in range(m):
table[0][0][j] = 1
table[1][0][j] = 0
for p in range(2):
for i in range(1, n + 1):
for j in range(m):
y = table[p][i][j - 1] if j >= 1 else 0
x = table[1 - p][i - S[j]][j] if i - S[j] >= 0 else 0
table[p][i][j] = x + y
return table[0][n][m - 1]
However, this approach is not creating the right tables for parity equal to 0 and equal to 1:
[1, 1, 1]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[1, 1, 1]
[0, 1, 1]
[0, 0, 1]
[0, 0, 0]
How can I adequately implement a tabulation approach for the given recursion relation?

Resources