1
frmongo OP 有没有大神感兴趣怎么实现,我自己实现的 code 不具备通用性,所以想参考下其他人的想法。目前问题纠结在,如何实现在遍历 list 的过程中还可能会删除多个元素的这个操作上
|
2
codingKingKong 2018-08-28 11:52:48 +08:00
@frmongo 我用递归写了一个, 也仅仅在给出的这个上运行正常
|
3
siteshen 2018-08-28 12:45:38 +08:00
# 实现了一个简单版的,不过有个假定:heads 和 tails 是各自唯一的。
# 如果不是唯一,可以对各个元素增加一个 count 字段,然后比较。 def merge(list_of_list): heads = {a for (a, b) in list_of_list} tails = {b for (a, b) in list_of_list} return heads - tails print(merge([[1,2],[2,3],[3,4],[4,7]])) # {1} print(merge([[1,2],[2,3],[3,4],[4,7],[7,1]])) # set() |
4
codingKingKong 2018-08-28 12:49:37 +08:00
package temp;
import java.util.ArrayList; import java.util.List; public class D { private List<Node> data = new ArrayList<>(); { data.add(new Node(1, 2)); data.add(new Node(2, 3)); data.add(new Node(3, 4)); data.add(new Node(4, 7)); data.add(new Node(1, 7)); } public static void main(String[] args) { D start = new D(); List<Node> nn = start.check(start.data); nn.forEach(n -> System.out.println(n.x + ":" + n.y)); } private List<Node> check(List<Node> nodes){ if (nodes.size() == 1) { return nodes; } List<Node> result = new ArrayList<>(); boolean can = false; for (int i = 0; i < nodes.size(); i++) { for (int j = i+1; j < nodes.size(); j++) { if (nodes.get(i).y == nodes.get(j).x) { result.add(new Node(nodes.get(i).x, nodes.get(j).y)); i++; can = true; break; }else { if (!result.contains(nodes.get(i))) { result.add(nodes.get(i)); } if (!result.contains(nodes.get(j))) { result.add(nodes.get(j)); } } } if (i == nodes.size() -1) { if (!result.contains(nodes.get(i))) { result.add(nodes.get(i)); } } } if (can) result = check(result); return result; } class Node{ Node(int x, int y) { this.x = x; this.y = y; } int x; int y; } } |
5
frmongo OP 我写了一个,但是 fusion 是一个有缺陷的函数,需要改进
from random import choice def combine_two(a,b): c = [None,None] if a[1]==b[0]: c[0]=a[0] c[1]=b[1] elif b[1] == a[0]: c[0]=b[0] c[1]=a[1] return c def fusion(list): ss = list[:] nn = len(ss) for i in range(100): ele_1 = choice(ss) ele_2 = choice(ss) c = combine_two(ele_1,ele_2) if c != [None,None]: ss.remove(ele_1) ss.remove(ele_2) ss.append(c) return ss def check(list): n = len(list) for i in range(n): for j in range(n): if i != j: if list[i][0] == list[j][0] and list[i][1] == list[j][1]: return False return True jj = [[2,3],[3,4],[1,2],[4,7],[11,13],[1,7]] m = fusion(jj) print m n = check(m) print n |
6
aaaaasam 2018-08-30 14:12:56 +08:00
```python
list_a = [[1,2],[2,3],[3,4],[4,7],[1,7]] for i in list_a: list_test = [(i[0],x[1]) for x in list_a if i != x and i[1] == x[0]] if list_test: print(i, list_test) ``` |