matrix multiplication without numpy - python

#Here I should get [[1,3,4],[2,5,7],[5,9,6]] as my final output but Instead im getting [[5,9,6],[5,9,6],[5,9,6]]
def matrix_mul(A, B):
m1 = len(A)
n1 = len(A[0])
m2 = len(B)
n2 = len(B[0])
if(n1!=m2):
print("Not Possible")
else:
c = [[0]*n2]*m1
for i in range(m1):
for j in range(n2):
total = 0
for k in range(n1):
total += A[i][k] * B[k][j]
c[i][j]=total
return c
A = [[1,3,4],[2,5,7],[5,9,6]]
B = [[1,0,0],[0,1,0],[0,0,1]]
print("AxB\n",matrix_mul(A, B))

Change c = [[0]*n2]*m1 to
c = [[0]*n2 for _ in range(m1)]

Related

Pythagorean triple with python

I want to get a number 'n' and produce Pythagorean triple that total of them is equal with 'n'.
for example for n=12 my output is 3, 4, 5 (12 = 3 + 4 + 5).
I write below code but it take a lot of time for big numbers. please help me to improve it.
a = int(input())
done = False
for i in range(int(a/4)+1,2,-1):
if done:
break
for j in range(i+1,int(a/2)+1):
k = a-(i+j)
if k <= j:
break
if i**2 + j**2 == k**2:
print(i,j,k)
done = True
break
if done == False:
print('Impossible')
This code may help you
limits = int(input())
c, m = 0, 2
# Limiting c would limit
# all a, b and c
while c < limits :
# Now loop on n from 1 to m-1
for n in range(1, m) :
a = m * m - n * n
b = 2 * m * n
c = m * m + n * n
# if c is greater than
# limit then break it
if c > limits :
break
if a+b+c == limits:
print(a, b, c)
m = m + 1
>> 12
>> 3 4 5
I've used the joblib module to parallelize your code, though I haven't tested if there is a speedup for very large n; let me know:
from joblib import Parallel, delayed
done = False
def triple(a):
global done
for i in range(int(a/4)+1,2,-1):
if done:
break
for j in range(i+1,int(a/2)+1):
k = a-(i+j)
if k <= j:
break
if i**2 + j**2 == k**2:
print(i,j,k)
done = True
break
if done == False:
print('Impossible')
if __name__ == '__main__':
a = int(input("n:"))
Parallel(n_jobs=-1, backend="threading")(map(delayed(triple), [a]))
To generate a Pythagorean triplet of a given sum, you can run two loops, where the first loop runs from i = 1 to n/3, the second loop runs from j = i+1 to n/2. In second loop, we check if (n – i – j) is equal to i * i + j * j.
n = int(input()
for i in range(1, int(n / 3) + 1):
for j in range(i + 1, int(n / 2) + 1):
k = n - i - j
if (i * i + j * j == k * k):
print(i, j, k)

Creating a general function

I have a function defintion -
Now I have to create a function like this-
The problem is that since there are 4 combinations of (t,c)(where t is the feature and c is the class) which can occur that is (t,c) , (t',c) , (t,c') , (t', c'). So according to the values of t,c the function defintion will also change.
Is there any method apart from calculating a , b ,c ,d 4 times and then summing the function values?
The dataset looks like this-
feature file_frequency_M file_frequency_B
abc 2 5
my attempt-
dataset = pd.read_csv('.csv')
score = []
###list =[(t,c) ,(t,c0),(t0,c),(t0,c0)] ##representation of the combination of (t,c)
l=152+1394
for index, row in dataset.iterrows():
a = row['file_frequency_M']
b = row['file_frequency_B']
c = 152 - a
d = 1394 - b
temp_score = 0
tmp1 = 0
tmp2 = 0
tmp3 = 0
tmp4 = 0
for i in range(4):
if i == 0:
if a == 0:
tmp1 = 0
else:
tmp1 = log10(((a * l) / (a + c) * (a + b)))
temp_score += tmp1
if i == 1:
if b == 0:
tmp2 = 0
else:
tmp2 = log10(((b * l) / (b + d) * (b + a)))
temp_score += tmp2
if i == 2:
if c == 0:
tmp3 = 0
else:
tmp3 = log10(((c * l) / (c + a) * (c + d)))
temp_score += tmp3
if i == 3:
if d == 0:
tmp4 = 0
else:
tmp4 = log10(((d * l) / (d + b) * (d + c)))
temp_score += tmp4
score.append(temp_score)
np.savetxt("m.csv", score, delimiter=",")
You can save a lot of code repetition by creating a function representation of I(t,c):
import numpy as np
import pandas as pd
from math import log10
dataset = pd.read_csv('.csv')
score = []
###list =[(t,c) ,(t,c0),(t0,c),(t0,c0)] ##representation of the combination of (t,c)
l=152+1394
def I(a,b,c,n):
"""Returns I(t,c) = A*N/((A+C)*(A+B))"""
if a == 0:
return 0
return log10((a * n) / ((a + c) * (a + b)))
for index, row in dataset.iterrows():
a = row['file_frequency_M']
b = row['file_frequency_B']
c = 152 - a
d = 1394 - b
tmp1 = I(a,b,c,l)
tmp2 = I(b,a,d,l)
tmp3 = I(c,d,a,l)
tmp4 = I(d,c,b,l)
temp_score = sum(tmp1,tmp2,tmp3,tmp4)
score.append(temp_score)
np.savetxt("m.csv", score, delimiter=",")
Note: you appear to have an error in your code, according to the image of your function definition, it should be:
log10((a * n) / ((a + c) * (a + b)))
not
log10(((a * l) / (a + c) * (a + b)))
(note the parentheses placement).

Redundant lines in 0/1 Matrix output

I am trying to create a script that can allows me to output all the different combinations possible for different project optimization choices. In short, there are 6 projets (A B C D E F) that each have 2, 3 or 6 possible choices of optimization, that are mutually exclusive (you can't choose F4 and F5 at the same time for example).
import numpy as np
A = range(1, 3)
B = range(1, 3)
C = range(1, 7)
D= range(1,3)
E=range(1,3)
F=range(1,4)
length = len(A) + len(B) + len(C) + len(D) + len(E) + len(F)
nb_projet = len(A) * len(B) * len(C) * len(D) * len(E) * len(F)
result = np.zeros((length, nb_projet))
for k in range(len(A)):
for i in range(len(A)):
for j in range(nb_projet):
result[i, j] = (i+j % len(A)) == k
for k in range(len(B)):
for i in range(len(B)):
for j in range(nb_projet):
result[i + len(A), j] = (i+j % len(B)) == k
for k in range(len(C)):
for i in range(len(C)):
for j in range(nb_projet):
result[i + len(A)+len(B), j] = (i+j % len(C)) == k
for k in range(len(D)):
for i in range(len(D)):
for j in range(nb_projet):
result[i + len(A)+len(B)+len (C), j] = (i+j % len(D)) == k
for k in range(len(E)):
for i in range(len(E)):
for j in range(nb_projet):
result[i + len(A)+len(B)+len (C)+len(D), j] = (i+j % len(E)) == k
for k in range(len(F)):
for i in range(len(F)):
for j in range(nb_projet):
result[i + len(A)+len(B)+len (C)+len(D)+len(E), j] = (i+j % len(F)) == 0
print (result.T)
np.savetxt("ResultsS2.txt", result, delimiter=" ")
Basically the code is supposed to add a 1 if the optimization is chosen. At the moment it only generates 6 differents scenarios and not the 250+ that are possible.
Does anyone have an idea on how to fix this ?
Thank yu a lot !
This is just a bunch of concatenated one-hot arrays, so utilizing the second answer here and meshgrid to create the full factorial, you can just do something like this:
projects = [2,2,6,2,2,3] #[A.size, B.size, C.size . . .]
m = np.meshgrid(*[np.arange(i) for i in projects])
oneHots = [np.eye(projects[i])[m[i].flat] for i in range(len(projects))]
out = np.hstack(oneHots).T
out.shape
>(17, 288)
You can use something like this. Not the smartest, but if the arrays are not too long, it would work perfectly.
import numpy as np
A = range(0, 2)
B = range(0, 2)
C = range(0, 6)
length = len(A) + len(B) + len(C)
nb_projet = len(A) * len(B) * len(C)
result = np.zeros((length, nb_projet))
selectedList = []
count = 0
for i in A:
for j in B:
for k in C:
result[(i,count)]= 1
result[(len(A)+j,count)]=1
result[(len(A)+len(B)+k, count)] = 1
count+=1
Note, that I had changed the ranges to fit better.

How to find the number of times function f is executed?

The function f is defined as such:
def f(a, b):
if a <= 0 or b <= 0:
return a + b
else:
s = 0
if b * b % (a + b) != 0:
s += f(a, b - 3)
if a * a % (a + b) != 0:
s += f(a - 2, b)
if a == b - 1:
s += f(a - 3, b - 2)
return s
The question is: "How many times will a function "f" be executed, given f(4, 9)?" For example, for f(0, 0) function "f" will be executed once, since the first time is taken into account as well. Can someone explain to me, how I can find the number of executions? (Examples will be ideal.) Than you in advance!
You can attach an attribute to the function:
def f(a, b):
f.num += 1
if a <= 0 or b <= 0:
...
Result:
>>> f.num = 0
>>> f(0, 0)
0
>>> print(f.num)
1
>>> f.num = 0
>>> f(3, 5)
4
>>> print(f.num)
13
You can increment a global counter, an int wrapped in a list, incrementing it in the function and printing the result after you call it:
i = [0]
def f(a, b):
i[0] += 1
if a <= 0 or b <= 0:
return a + b
else:
s = 0
if b * b % (a + b) != 0:
s += f(a, b - 3)
if a * a % (a + b) != 0:
s += f(a - 2, b)
if a == b - 1:
s += f(a - 3, b - 2)
return s
f(2, 34)
print(i[0])
I don't trust Global variable because of the highly available scope i.e. global variables are accessible to everyone. Instead, you can keep a recursion variable which counts the number of times the function has been called.
def f(a, b, count=0):
count+=1
if a <= 0 or b <= 0:
return [a + b, count]
else:
s = 0
if b * b % (a + b) != 0:
l = f(a, b - 3,count)
s += l[0]
count+=l[1]
if a * a % (a + b) != 0:
l = f(a - 2, b, count)
s += l[0]
count+=l[1]
if a == b - 1:
l = f(a - 3, b - 2, count)
s += l[0]
count+=l[1]
return [s,count]

How to implement base b expansion in Python?

I have to implement this pseudo-code (from a discrete math book):
procedure base b expansion(n,b: positive integers with b>1
q :=n
k :=0
while q does not equal 0
a_k := q mod b
q = q div b
k = k + 1
return (a_k-1, .... a_1, a_0) {(a_k-1... a_1a_0)_b is the base expansion of n}
Here is my code thus far:
def expansion(n,b):
q = n
k = 0
a = []
i = len(str(n))
for x in range(0,1000):
a.append(0)
while q != 0:
a[k] = q % b
q = q / b
return a[k]
print expansion(444,2)
I just cant figure out what I am doing wrong, it usually says the index is out of bounds or it doesn't print enough numbers.
In your code you are not updating k,
while q != 0:
a[k] = q % b
q = q / b
# You need to update k
k += 1
Also, you need to return only a, not a[k].
Also, understand that for the current argument (444,2) you need at least 1085 places in the array before q becomes zero. You do not need to assign based on an index, but rather append the values to the list as they are computed.
So,
def expansion(n,b):
q = n
k = 0
a = []
i = len(str(n))
while q != 0:
a.append(q % b)
q = q / b
k += 1
return a
This way you avoid having to allocate places before hand.
Rather than using a list to accumulate digits, try a string. As you get a digit, concatenate it to the front of the string. Like so:
>>> def n_as_base_b(n, b):
... output = ""
... while n >0:
... output = str(n%b) + output
... n /= b
... return output
...
>>> n_as_base_b(15,2)
'1111'
>>> n_as_base_b(11,2)
'1011'

Categories