# conding:utf8
# author:mylittlegoblin
import pytest
class Three_list():
def three_list(self, nums):
res = []
nums.sort() # 首先机进行大小排序
for index_x in range(0, len(nums) - 2): # len(nums)-2 避免重复计算
if nums[index_x] > 0: # 如果第一个数大于零的话 后面的数相加肯定大于0 无需计算
break
if index_x > 0 and nums[index_x] == nums[index_x - 1]: # 如果相邻的两个数据相等则退出运算
break
index_y, index_z = index_x + 1, len(nums) - 1
while index_y < index_z:
sum_nums = nums[index_x] + nums[index_y] + nums[index_z]
if sum_nums < 0: # 总和小于零时把中间数右移以增大数值
index_y += 1
elif sum_nums > 0: # 总和大于零时把尾数左移以减少数值
index_z -= 1
else:
res.append([nums[index_x], nums[index_y], nums[index_z]]) # 符合条件的计入res中
while index_y < index_z and nums[index_y] == nums[index_y + 1]: # 避免重复数据计算
index_y += 1
while index_y < index_z and nums[index_z] == nums[index_z - 1]:
index_z -= 1
index_y += 1
index_z -= 1
if res == []:
return "该数组无解"
else:
return res
def test_three_list():
test_list = [-1, 0, 1, 2, -1, -4]
third_list = Three_list()
print(third_list.three_list(test_list))