test_unionfind.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import networkx as nx
  2. def test_unionfind():
  3. # Fixed by: 2cddd5958689bdecdcd89b91ac9aaf6ce0e4f6b8
  4. # Previously (in 2.x), the UnionFind class could handle mixed types.
  5. # But in Python 3.x, this causes a TypeError such as:
  6. # TypeError: unorderable types: str() > int()
  7. #
  8. # Now we just make sure that no exception is raised.
  9. x = nx.utils.UnionFind()
  10. x.union(0, "a")
  11. def test_subtree_union():
  12. # See https://github.com/networkx/networkx/pull/3224
  13. # (35db1b551ee65780794a357794f521d8768d5049).
  14. # Test if subtree unions hare handled correctly by to_sets().
  15. uf = nx.utils.UnionFind()
  16. uf.union(1, 2)
  17. uf.union(3, 4)
  18. uf.union(4, 5)
  19. uf.union(1, 5)
  20. assert list(uf.to_sets()) == [{1, 2, 3, 4, 5}]
  21. def test_unionfind_weights():
  22. # Tests if weights are computed correctly with unions of many elements
  23. uf = nx.utils.UnionFind()
  24. uf.union(1, 4, 7)
  25. uf.union(2, 5, 8)
  26. uf.union(3, 6, 9)
  27. uf.union(1, 2, 3, 4, 5, 6, 7, 8, 9)
  28. assert uf.weights[uf[1]] == 9
  29. def test_unbalanced_merge_weights():
  30. # Tests if the largest set's root is used as the new root when merging
  31. uf = nx.utils.UnionFind()
  32. uf.union(1, 2, 3)
  33. uf.union(4, 5, 6, 7, 8, 9)
  34. assert uf.weights[uf[1]] == 3
  35. assert uf.weights[uf[4]] == 6
  36. largest_root = uf[4]
  37. uf.union(1, 4)
  38. assert uf[1] == largest_root
  39. assert uf.weights[largest_root] == 9
  40. def test_empty_union():
  41. # Tests if a null-union does nothing.
  42. uf = nx.utils.UnionFind((0, 1))
  43. uf.union()
  44. assert uf[0] == 0
  45. assert uf[1] == 1