Menu
CoddyTech

Set Difference

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 35 of 78.

The difference of two sets holds the members of the first set that are not in the second. Loop over the first set and keep what the second set lacks:

var needed := {"rope": true, "torch": true, "map": true}
var packed := {"torch": true, "apple": true}
var missing := {}
for item in needed:
	if not packed.has(item):
		missing[item] = true
print(missing.keys()) # ["rope", "map"]

The order of the sets matters. The difference of packed and needed is ["apple"]: what you packed but did not need.

The two differences together form the symmetric difference: the members that are in exactly one of the sets. Here that is rope, map and apple.

To check that nothing is missing, has_all() takes an array and returns true when every element of it is a key of the dictionary:

print(packed.has_all(needed.keys())) # false: rope and map are missing
challenge icon

Challenge

Easy

Before a trip, you compare what you need with what you packed. The program reads two lines, the needed items and the packed items, separated by spaces, and the starter code builds the sets needed and packed.

Print two lines, with the members joined by , :

  • Missing: followed by the needed items that are not packed
  • Extra: followed by the packed items that are not needed

Keep the order of the set you loop over. Print none instead of an empty list. For the input:

rope torch map
torch apple

the output is:

Missing: rope, map
Extra: apple

Try it yourself

extends Node

func _ready():
	var needed := {}
	for item in OS.read_string_from_stdin().split(" ", false):
		needed[item] = true
	var packed := {}
	for item in OS.read_string_from_stdin().split(" ", false):
		packed[item] = true

	# Build the two differences

	# Print the results
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler