s = set()
for i in range(10):
s.add(i)
s.add(4)
s.add(8)
print(s)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
s.remove(3)
print(s)
{0, 1, 2, 4, 5, 6, 7, 8, 9}
1 in s
True
271 in s
False
s = set()
We can't add things to a set like a list that are "mutable" (i.e. can be changed during runtime), because it is impossible to come up with a hash code for them that is guaranteed to be unique
s.add([1, 2])
instead, if we want to add things that are grouped together in a list-like structure, we should use a tuple, which is "immutable" (i.e. not allowed to be changed during runtime)
s.add((1, 2))
class Wizard:
def __init__(self, name, month, day, year):
self.name = name
self.month = month
self.day = day
self.year = year
def __hash__(self):
return self.day*12 + self.month
def get_all_info_str(self):
return "{}: {}/{}/{}".format(self.name, self.month, self.day, self.year)
def __eq__(self, other):
return self.name == other.name and self.month == other.month and self.day == other.day and self.year == other.year
def __str__(self):
return self.name
def get_all_wizards():
"""
Return a list of all of the wizards in the database
"""
wizards = []
fin = open("HarryPotter.csv")
for line in fin.readlines():
name, month, day, year = line.split(",")
wizards.append(Wizard(name, int(month), int(day), int(year)))
return wizards
wizards = set()
for w in get_all_wizards():
wizards.add(w)
for w in wizards:
print(w)
Albus Dumbledore Vincent Crabbe Olivander Molly Weasley Arthur Weasley Draco Malfoy Padma Patil Paravi Patil Tom Riddle Bill Weasley Harry Potter Lavender Brown Blaise Zabini Cedric Diggory Dean Thomas Flilus Flitwick Rita Skeeter Ron Weasley Fred Weasley George Weasley Hermione Granger Sybil Trelawney Bellatrix Lestrange Peter Pettigrew James Potter Luna Lovegood Neville Longbottom Lucius Malfoy Ginny Weasley Argus Filch Katie Bell Pansy Parkinson Seamus Finnigan Minerva McGonagall Pomona Sprout Cornelius Fudge Cho Chang Lily Potter Percy Weasley Rubeus Hagrid Fleur Delacour Gregory Goyle Remus Lupin Kingsley Shacklebolt Severus Snape Sirius Black
A dictionary is just like a set, except we store an extra piece of information tacked onto the elements. The item that's hashed is called the "key," and the associated information is called the "value". In the example below, keys are strings, and values are ints
d = {"theo":10, "layla":9, "chris":33} # dictionary
print(d["theo"])
d["celia"] = 32
print(d)
10 {'theo': 10, 'layla': 9, 'chris': 33, 'celia': 32}
d[(1, 2)] = "something"
print(d)
{'theo': 10, 'layla': 9, 'chris': 33, 'celia': 32, (1, 2): 'something'}