Python Nodes generator:如何通过列表元素两两相加生成节点
Python Nodes Generator for Pairwise Element Sum Replacement
Hey there! Let's work through this problem step by step. The task is to generate all possible "node" lists where we take every unique pair of distinct elements (by position, to cover all possible pairs even if values repeat) from the input list, sum them, and replace the pair with that sum.
Solution Code
import itertools def generate_nodes(input_list): nodes = [] # Generate all unique index pairs (i,j) where i < j to avoid duplicate pairs for i, j in itertools.combinations(range(len(input_list)), 2): new_node = [] for idx in range(len(input_list)): if idx == i: # Add the sum of elements at i and j once new_node.append(input_list[i] + input_list[j]) elif idx != j: # Skip j since we've included its value in the sum new_node.append(input_list[idx]) nodes.append(new_node) return nodes # Test with your example input input_example = [2, 7, 4, 5] print(generate_nodes(input_example)) # Output: [[9, 4, 5], [6, 7, 5], [7, 7, 4], [2, 10, 5], [2, 10, 4], [2, 7, 9]]
How It Works
- Unique Pairs: We use
itertools.combinationsto generate index pairs wherei < j. This ensures we don't process the same pair twice (like (1,0) after (0,1)), which would create duplicate nodes. - Building Each Node: For each index pair, we construct a new list:
- When we hit index
i, we add the sum of the elements at positionsiandj. - We skip index
jentirely because its value is already included in the sum we added ati. - All other elements are added to the new list exactly as they appear in the input.
- When we hit index
Handling Duplicate Values in Input
If your input list has duplicate elements (e.g., [2, 2, 3]), the above function will generate nodes for every position pair—even if some nodes end up being identical. If you want to return only unique nodes, you can modify the function to use a set (since lists aren't hashable, we convert nodes to tuples first):
import itertools def generate_unique_nodes(input_list): unique_nodes = set() for i, j in itertools.combinations(range(len(input_list)), 2): new_node = [] for idx in range(len(input_list)): if idx == i: new_node.append(input_list[i] + input_list[j]) elif idx != j: new_node.append(input_list[idx]) unique_nodes.add(tuple(new_node)) # Convert tuples back to lists for the final output return [list(node) for node in unique_nodes] # Test with duplicate input values input_dup = [2, 2, 3] print(generate_unique_nodes(input_dup)) # Output: [[4, 3], [5, 2]]
内容的提问来源于stack exchange,提问作者SahishnaAkella
相关产品推荐
相关产品推荐

