External Exam Download Resources Web Applications Games Recycle Bin

sets.py

#A set is an unordered collection of unique objects: 
a = {1, 2, 3}
b = {3, 4, 5}
b.add(6)
b.remove(6)

print(a)
print(b)

print(a.union(b)) #Python 3.X: (a | b)
print(a.intersection(b)) #Python 3.X: (a & b)
print(a.difference(b)) #Python 3.X: (a - b)
print(b.difference(a)) #Python 3.X: (b - a)
print(a.symmetric_difference(b)) #Python 3.X: (a ^ b)

# Union = {1, 2, 3, 4, 5}
# Intersection = {3}
# Difference of a - b = {1, 2}
# Difference of b - a = {4, 5}
# Symmetric difference = {1, 2, 4, 5}


sets intro.py

moves = set()
moves.add("Barrel Roll")
moves.add("Zerg Rush")

print("Moves remaining:", moves)

if "Zerg Rush" in moves:
    print("Now doing a Zerg Rush!")
    moves.remove("Zerg Rush")

print("Moves remaining:", moves)


  1. Write a program that uses a set to add each of my guesses in a game of Battleships. If i have already guessed the co-ords, then the program should tell me:
    Guess: A3 
    Targeting A3 
    Guess: C4 
    Targeting C4 
    Guess: A3 
    You've chosen those co-ordinates already 
    Guess: B2 
    Targeting B2

  2. ask your friend for 3 of their favourite foods. record this in a set. record your own favourite 3 foods too in another set. Use set theory to find patterns between your favourite foods and your friends favourite foods, e.g. what do you have in common? What do you like that your friend doesn't? etc.