Skip to content

Question 23

The following program prints out a set named result at the end for each item in list all.

set_a, set_b, set_c = set("one"), set("two"), set("three")
all = [set_a ^ set_b, set_a ^ set_c, set_b ^ set_c]

for this_set in all:
    the_rest = all[:]
    the_rest.remove(this_set)

    for item in the_rest:
        result = this_set & item
        print(result)

Out of all the possible values of result printed from this program, what is the greatest number of elements possible? [3 marks]

Solution

We initialize 3 sets:

  • set_a: set("one") = {'o', 'n', 'e'}
  • set_b: set("two") = {'t', 'w', 'o'}
  • set_c: set("three") = {'t', 'h', 'r', 'e'} (duplicate 'e' is removed)
Note

Each time you print a set, the elements may appear in a different order from the previous run. For simplicity, the original order will be maintained or an ascending order will be deployed.

We now have set all which comprises of the following elements:

  • set_a ^ set_b: {'o', 'n', 'e'} ^ {'t', 'w', 'o'} = {'n', 'e', 't', 'w'}
  • set_a ^ set_c: {'o', 'n', 'e'} ^ {'t', 'h', 'r', 'e'} = {'o', 'n', 't', 'h', 'r'}
  • set_b ^ set_c: {'t', 'w', 'o'} ^ {'t', 'h', 'r', 'e'} = {'w', 'o', 'h', 'r', 'e'}

For each of these ^ set operations, obtain 1 instance of each unique item that is found in either set but not both. Hence, all = [{'n', 'e', 't', 'w'}, {'o', 'n', 't', 'h', 'r'}, {'w', 'o', 'h', 'r', 'e'}].

The program then iterates through all as follows:

this_set the_rest item result: this_set & item len(result)
{'n', 'e', 't', 'w'} [{'o', 'n', 't', 'h', 'r'}, {'w', 'o', 'h', 'r', 'e'}] {'o', 'n', 't', 'h', 'r'} {'n', 't'} 2
{'n', 'e', 't', 'w'} {'w', 'o', 'h', 'r', 'e'} {'e', 'w'} 2
{'o', 'n', 't', 'h', 'r'} [{'n', 'e', 't', 'w'}, {'w', 'o', 'h', 'r', 'e'}] {'n', 'e', 't', 'w'} {'n', 't'} 2
{'o', 'n', 't', 'h', 'r'} {'w', 'o', 'h', 'r', 'e'} {'o', 'h', 'r'} 3
{'w', 'o', 'h', 'r', 'e'} [{'n', 'e', 't', 'w'}, {'o', 'n', 't', 'h', 'r'}] {'n', 'e', 't', 'w'} {'w', 'e'} 2
{'w', 'o', 'h', 'r', 'e'} {'o', 'n', 't', 'h', 'r'} {'o', 'h', 'r'} 3

The largest value(s) of result always arrives at length 3.

Answer

3 elements