Skip to content

Instantly share code, notes, and snippets.

@bmontana
Created March 21, 2018 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmontana/9c6ab8d325194e25a38768368d9219da to your computer and use it in GitHub Desktop.
Save bmontana/9c6ab8d325194e25a38768368d9219da to your computer and use it in GitHub Desktop.
Computes the inner product of two arrays (lists). The lists must be the same length as each other. The inner product is the sum of the products of elements with matching indices from each array.
# U11_Ex07_InnerProd.py
#
# Author: Bill Montana
# Course: Coding for OOP
# Section: A3
# Date: 20 Mar 2018
# IDE: PyCharm Community Edition
#
# Assignment Info
# Exercise: 7
# Source: Python Programming
# Chapter: 11
#
# Program Description
# Computes the inner product of two arrays (lists). The lists must be the same
# length as each other. The inner product is the sum of the products of elements
# with matching indices from each array.
#
# Algorithm (pseudocode)
# ensure lists are same-length; throw an error if not
# initialize an accumulator to zero
# iterate over the length of the lists
# sum the products of elements with matching indices to the accumulator
# return the sum
def innerProd(list1, list2):
"""
Computes the inner product of list1 and list2
:param list1: list -> first list (elements are either int or float)
:param list2: list -> second list (elements are either int or float)
:return: int or float -> inner product
"""
try:
a = list2[len(list1)-1]
b = list1[len(list2)-1]
except IndexError:
return "Lists must be of same length."
# quit(1)
innerProd = 0
for i in range(len(list1)):
innerProd += list1[i] * list2[i]
return innerProd
if __name__ == '__main__':
print(innerProd([1,2], [4,5,6]))
@bmontana
Copy link
Author

RESULTS:
========
innerProd([1,2,3], [4,5,6])   -->                              32 |                              32 | [ Pass ]
innerProd([1,2,3], [4,5])     -->   Lists must be of same length. |   Lists must be of same length. | [ Pass ]
innerProd([1,2], [4,5,6])     -->   Lists must be of same length. |   Lists must be of same length. | [ Pass ]
innerProd([], [4,5,6])        -->   Lists must be of same length. |   Lists must be of same length. | [ Pass ]
innerProd([1,2,3], [])        -->   Lists must be of same length. |   Lists must be of same length. | [ Pass ]
========

Note that I made innerProd() return the string "Lists must be of same length." for testing purposes. My original code printed the message, then quit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment