Skip to content

Instantly share code, notes, and snippets.

@SigmaThetaTech
Created May 17, 2023 21:11
Show Gist options
  • Save SigmaThetaTech/6c5b7e0fd74b6e5c38068e609702c078 to your computer and use it in GitHub Desktop.
Save SigmaThetaTech/6c5b7e0fd74b6e5c38068e609702c078 to your computer and use it in GitHub Desktop.
Algorithm for finding the dot product of 2 arrays written in Python for MIT Open Learning Library on Machine Learning (MITx - 6.036)
# Written by SigmaTech
# Beat a Computer Science graduate at desigining this algorithm at the same start time
# Make sure that the columns of M1 match the rows of M2
# Create an answer array M3
# For each entry (array) of M1,
def getRowsColumns(V):
return (len(V), len(V[0]))
def array_mult(A, B):
finalAnswer = []
# Store the number of columns and rows for the results
resultRows = getRowsColumns(A)[0]
resultColumns = getRowsColumns(B)[1]
#print("Dimensions of A", getRowsColumns(A))
#print("Dimensions of B", getRowsColumns(B))
#print("Dimensions of result:", (resultRows, resultColumns))
# Make sure that the columns of A match the rows of B
dim_A = getRowsColumns(A)
dim_B = getRowsColumns(B)
if dim_A[1] != dim_B[0]:
return None
# Create our blank answer
C = []
for currentRow in range(resultRows):
newRowToAppendToAnswer = []
for currentColumn in range(resultColumns):
# Sum up all the products for the corresponding entries in each array
sum = 0
# For every entry in A[currentRow], multiply by B[currentColumn][currentRow] and add to sum
for A_column, entry in enumerate(A[currentRow]):
product = entry * (B[A_column][currentColumn])
sum = sum + product
print("Multiplying", entry, "by", (B[A_column][currentColumn]), "=", product)
newRowToAppendToAnswer.append(sum)
print("For row", currentRow, "column", currentColumn, "we got", sum)
finalAnswer.append(newRowToAppendToAnswer)
return finalAnswer
# TEST STUFF
M1 = [[1, 2, 3], [-2, 3, 7]]
M2 = [[1,0,0],[0,1,0],[0,0,1]]
ans = array_mult(M1, M2)
print(ans)
M1 = [[1, 2, 3], [-2, 3, 7]]
M3 = [[1], [0], [-1]]
ans = array_mult(M1, M3)
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment