我在面试中遇到一个问题,这是很有挑战性的。本课题以决策分析为基础。问题是,让我们假设我们有一个元组;
(15, 8, 8, 3)我们想要创建所有组合的所有和一个一个,而不重复和求和相同的数字,如这个输出;
[(23, 8, 3), (18, 8, 8), (15, 11, 8)]另一个例子;
(6, 5, 3, 8)产出如下:
[(11, 3, 8), (9, 5, 8), (14, 5, 3), (6, 8, 8), (6, 13, 3), (6, 5, 11)]注意:订单是灵活的。
我真的很想知道答案,所以如果有人对这个编码挑战感兴趣,可以帮助我改进我的思维结构。
发布于 2018-03-11 19:42:22
In[2]: from itertools import combinations
...:
...:
...: def solution(nums):
...: result = []
...: seen = set()
...: for p in combinations(range(len(nums)), r=2):
...: dex_1, dex_2 = p
...: if nums[dex_1] == nums[dex_2]:
...: continue
...: current = []
...: for i, elem in enumerate(nums):
...: if i == dex_1:
...: current.append(elem + nums[dex_2])
...: elif i != dex_2:
...: current.append(elem)
...: sorted_current = tuple(sorted(current))
...: if sorted_current not in seen:
...: result.append(tuple(current))
...: seen.add(sorted_current)
...: return result
...:
In[3]: solution((15, 8, 8, 3))
Out[3]: [(23, 8, 3), (18, 8, 8), (15, 11, 8)]
In[4]: solution((6, 5, 3, 8))
Out[4]: [(11, 3, 8), (9, 5, 8), (14, 5, 3), (6, 8, 8), (6, 13, 3), (6, 5, 11)]发布于 2018-03-19 11:11:00
您可以尝试这种方法:
import itertools
final_=[]
for m in list(itertools.permutations(order,r=4)):
if m[:2][0]==m[:2][1]:
pass
else:
final_.append(tuple(sorted((sum(m[:2]),)+m[2:])))
print(set(final_))产出:
when order=(15, 8, 8, 3)产出:
{(3, 8, 23), (8, 8, 18), (8, 11, 15)}当order=(6, 5, 3, 8)
产出:
{(5, 8, 9), (3, 8, 11), (3, 5, 14), (6, 8, 8), (5, 6, 11), (3, 6, 13)}https://stackoverflow.com/questions/49224066
复制相似问题