The other week for my algorithms class I needed to find the minimum dot product of a list. My first try at a solution, which threw an error, was this:
def min_dot_product(a, b, n): a = sorted(a) b = sorted(b, reverse=True) res = 0 for i in range(n): res += a[i] * b[i] return res
Python has two different ways of sorting a list:
sorted(list[, reverse=False]). Why a method and a function to do the same thing? Let's look:
li = [5, 1, 4, 3, 2] li.sort() li >>> [1, 2, 3, 4, 5] li.sort(reverse=True) li >>> [5, 4, 3, 2, 1]
list.sort() sorts the list and returns None.
On the other hand,
sorted(list) sorts and returns the list
li = [5, 1, 4, 3, 2] sorted(li, reverse=True) >>> [5, 4, 3, 2, 1]
I've contributed the above to SO's Python documentation on lists and list methods.