DSUF-P5

Equal and not equal

Practice 5 of 5Union-find9 tests

The problem

Each fact says that two names are equal ("a==b") or not equal ("a!=b"). Equal is what you expect: if a equals b and b equals c, then a equals c. Return True if all the facts can hold at the same time, and False if they contradict each other.

consistent(["a==b", "b==c", "a!=c"])    # False
consistent(["a==b", "c!=a", "c==d"])    # True
consistent(["x!=x"])                    # False

Names are made of the letters a to z and can be longer than one letter, such as "delhi==dilli". There are no spaces.

Some tests join long chains. Write find with a loop, or make sure your trees stay short (lessons 2 and 3): a recursive find on a path of 100,000 nodes stops with RecursionError.

Limits

  • Up to 200,000 facts and about 200,000 different names.

Builds on DSUF-5 Applications.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Can all holdNot run
3Order of the factsNot run
4Not equal to itselfNot run
5Equal to itselfNot run
6Longer namesNot run
7No factsNot run
8A long chain, all fineNot run
9A long chain, one clashNot run