Making it faster
The maximum product of two numbers in the input will be either:
- the product of the two highest numbers
- the product of the two lowest numbers
- note that this is possible when the lowest numbers are negative
So you can find the two highest and two lowest values, and decide which product is higher and return it.
This can be done in \$O(n)\$ time,
which will be much faster than the current \$O(n^2)\$ solution for large inputs.
>>> pairwise_max_product([3, 2])
>>> pairwise_max_product([3, 2, -5, -6])
>>> pairwise_max_product([-2, 1, 1])
>>> pairwise_max_product([-2, -2, 1, 1])
assert len(nums) >= 2
def top2(key=lambda x: x):
second, first = sorted(nums[0:2], key=key)
for current in nums[2:]:
if key(first) < key(current):
second = first
first = current
elif key(second) < key(current):
second = current
return first, second
max1, max2 = top2()
min1, min2 = top2(lambda x: -x)
return max(max1 * max2, min1 * min2)
Beware of corner cases
If there are less than two numbers,
the program outputs 0.
For a list with a single element, say
printing that the maximum product of two pairs of numbers is 0 would seem strange.
Use descriptive variable names
It's hard to remember what is what,
when variables don't have descriptive names, such as
nums_count would help a lot.
The code reads input from
stdin, computes something, then prints to
The computation part can be turned into a function that takes a list of numbers and returns the maximum product.
It will have a single responsibility,
to compute the maximum product,
and a reader can focus on making it fulfill that one responsibility:
nums_count = len(nums).
Follow the style guide
Python has an official style guide PEP-8,
it's good to follow it.
it's recommended to put spaces around operators,
for example instead of
range(i + 1, b).