找出列表中两个数字的最大乘积。数字也可以是负数。代码正在运行,但测试程序发出 Time Limit Exceeded。如何优化?是否可以将现有的 2 for 转换为列表理解是很有趣的,因为我没能在 3 小时内做到这一点。
def composition():
s = [int(i) for i in input().split()]
lists = []
total = 0
for i in range(len(s)):
for j in range(len(s)):
if s[i] * s[j] > total and i != j:
total = s[i] * s[j]
lists.append(s[i])
lists.append(s[j])
a = lists[-1]
b = lists[-2]
if a < b:
return a, b
return b, a
print(*composition())
不使用任何库的最短代码:)
更短的解决方案:
好吧,如果您完全正面决定,那只是一个lobeshnik,那么
更好(更短):
我将假设序列中的数字是唯一的。Itertools.combinations非常适合查找所有可能的非重复组合。对于重复项 - combination_with_replacement。