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 missingChallenge
EasyBefore 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 packedExtra: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 applethe output is:
Missing: rope, map
Extra: appleTry 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler